JSON.Net的反序列化返回"null" [英] Deserialization of JSON.Net returns 'null'
本文介绍了JSON.Net的反序列化返回"null"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用JSON.Net反序列化JSON字符串. JSON字符串是
I am using JSON.Net to Deserialize a JSON string. The JSON string is
string testJson = @"{
""Fruits"": {
""Apple"": {
""color"": ""red"",
""size"": ""round""
},
""Orange"": {
""Properties"": {
""color"": ""red"",
""size"": ""round""
}
}
}
}";
我的代码是
public class Fruits
{
public Apple apple { get; set; }
public Orange orange { get; set; }
}
public class Apple
{
public string color { get; set; }
public string size { get; set; }
}
public class Orange
{
public Properties properties { get; set; }
}
public class Properties
{
public string color { get; set; }
public string size { get; set; }
}
我正在尝试使用以下代码对此进行反序列化
I am trying to Deserialize this with the following code
Fruits result = JsonConvert.DeserializeObject<Fruits>(testJson);
我的结果中存在一个问题,即苹果和橙色的水果具有null
而不是他们的属性,颜色,大小.
I have a problem in my result that Fruits with Apple and Orange has null
instead of their Properties , color , size.
推荐答案
假设您无法更改json,则需要创建一个具有Fruits
属性的新FruitsWrapper
类
Assuming you can't change the json, you need to create a new FruitsWrapper
class that has a Fruits
property
public class FruitsWrapper
{
public Fruits Fruits { get; set; }
}
并将json反序列化为FruitsWrapper
的实例而不是Fruits
and deserialize the json into an instance of FruitsWrapper
instead of Fruits
FruitsWrapper result = JsonConvert.DeserializeObject<FruitsWrapper>(testJson);
正在运行的演示: https://dotnetfiddle.net/nQitSD
这篇关于JSON.Net的反序列化返回"null"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文