JSON.Net的反序列化返回’null’
我正在使用JSON.Net来反序列化JSON字符串。 JSON字符串是
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; } }
我试图使用以下代码反序列化
Fruits result = JsonConvert.DeserializeObject(testJson);
我的结果有一个问题, Apple和Orange的 水果 null
而不是它们的属性 , 颜色 , 大小 。
假设您无法更改json,则需要创建一个具有Fruits
属性的新FruitsWrapper
类
public class FruitsWrapper { public Fruits Fruits { get; set; } }
并将json反序列化为FruitsWrapper
而不是Fruits
的实例
FruitsWrapper result = JsonConvert.DeserializeObject(testJson);
工作演示: https : //dotnetfiddle.net/nQitSD
问题是,Json中最外面的护腕对应于您尝试反序列化的类型。
所以这:
string testJson = @"{ ""Fruits"": { ... } }";
与Fruit相对应,因为那是你想要反序列化的东西。
string testJson = @"{ ""Fruits"": { ... } ^--+-^ | +-- this is assumed to be a property of this --+ | +------------------------+ | v--+-v Fruits result = JsonConvert.DeserializeObject(testJson);
但是, Fruits
类型没有名为Fruits
的属性,因此没有反序列化。
如果无法更改Json,则需要创建一个反序列化的容器类型,如下所示:
public class Container { public Fruits Fruits { get; set; } }
然后你可以反序列化:
Container result = JsonConvert.DeserializeObject(testJson);
JSON字符串应该是:
string testJson = @"{ ""Apple"": { ""color"": ""red"", ""size"": ""round""}, ""Orange"": { ""Properties"": { ""color"": ""red"", ""size"": ""round"" } } }";
与你的class级反序列化
您的JSON字符串不正确(正如其他人指出的那样),但我添加它以帮助您找到正确的格式。 鉴于你有这样的fruit
对象:
var fruit = new Fruits { apple = new Apple { color = "red", size = "massive" }, orange = new Orange { properties = new Properties { color = "orange", size = "mediumish" } } };
然后,您可以将其序列化为JSON:
var testJson = JsonConvert.SerializeObject(fruit);
现在您可以看到序列化输出将如下所示:(略有格式化)
{"apple": {"color":"red","size":"massive"}, "orange": {"properties": {"color":"orange","size":"mediumish"}}}
这很容易反序列化回你的对象:
fruit = JsonConvert.DeserializeObject(testJson);