好的,有一些关于这方面的帖子。。。我还没有让他们工作。
我有一个简单的对象
{
"Projects": "Projects",
"Dashboard": "Dashboard",
"Applications": "Applications",
"Plans": "Plans",
"Logout": "Logout"
}
我正在尝试反序列化它。我有Newtonsoft可用。
这是我所拥有的不起作用的东西。
var languageString = "{"Projects":"Projects","Dashboard":"Dashboard","Applications":"Applications","Plans":"Plans","Logout":"Logout"}";
var objOut = new { name = "", lastname = "" };
var result = JsonConvert.DeserializeAnonymousType(languageString, objOut);
我一直在匿名对象上收到一个错误。
如有任何帮助,我们将不胜感激。
感谢
要反序列化对象,需要确保用于反序列化对象的类或匿名类型与源JSON字符串匹配。
如果您有一个JSON { "name": "john", "lastname": "smith" }
,那么您的代码应该可以工作:
// I expect no one to have concerns about the double quots (""): it's
// another way of escaping quots in C# (you should also use " but it's
// uglier, isn't it? ;)
string jsonText = @"{ ""name"": ""john"", ""lastname"": ""smith"" }";
var sampleType = new { name = "", lastname = "" };
var deserializedObject = JsonConvert.DeserializeAnonymousType(jsonText, sampleType );
在你的情况下
您需要一个匿名类型实例示例,如下所示:
var sampleType = new
{
Projects = "",
Dashboard = "",
Applications = "",
Plans = "",
Logout = ""
}
或者使用动态对象呢
您还可以使用dynamic
将对象反序列化为ExpandoObject
,并且不需要示例类型!
dynamic deserializedObject =
JsonConvert.DeserializeObject(languageString, new ExpandoObjectConverter());
请记住,这是鸭子类型:直到运行时,您才知道反序列化对象是否具有预期的属性。顺便说一句,文档丰富的代码可以做到这一点,如果您希望反序列化的对象具有类似lastname
的属性,则可以使用deserializedObject.lastname
直接访问它!
var languageString = @"{""Projects"":""Projects"",""Dashboard"":""Dashboard"",""Applications"":""Applications"",""Plans"":""Plans"",""Logout"":""Logout""}";
var objOut = new { Projects = "", Dashboard = "", Applications = "", Plans = "", Logout = "" };
var result = JsonConvert.DeserializeAnonymousType(languageString, objOut);
这对你有用。
使用您的代码,我没有得到任何错误。请详细解释您的错误
我在JSON字符串中看不到name或lastname 逐字字符串: 反向冲击: 现在,当你正确处理了这个字符串后,如果你愿意反序列化JSON,你应该创建一个合适的类来匹配它 解决所有这些问题后,您将在匿名类的对象实例中检索JSON值。var languageString = @"{""Projects"":""Projects"",""Dashboard"":""Dashboard"",""Applications"":""Applications"",""Plans"":""Plans"",""Logout"":""Logout""}";
var languageString = "{"Projects":"Projects","Dashboard":"Dashboard","Applications":"Applications","Plans":"Plans","Logout":"Logout"}";
var objOut = new
{
Projects = "",
Dashboard = "",
Applications = "",
Plans = "",
Logout = ""
};
在我看来,反序列化为强类型类通常更容易。考虑到您提供的JSON,您的反序列化类将如下所示:
public class RootObject
{
public string Projects { get; set; }
public string Dashboard { get; set; }
public string Applications { get; set; }
public string Plans { get; set; }
public string Logout { get; set; }
}
尽管这个JSON相当简单,但如果它更复杂,您可以使用http://json2csharp.com以从JSON自动生成C#类。
那么你所需要做的就是:
var languageString = "{"Projects":"Projects","Dashboard":"Dashboard","Applications":"Applications","Plans":"Plans","Logout":"Logout"}";
var result = JsonConvert.DeserializeObject<RootObject>(languageString);