将JSON对象反序列化为类
我在将一个JSON对象反序列化到一个类(使用JSON.NET)时遇到了一些麻烦,并希望有人能指出我朝着正确的方向。下面是代码,我想一个片段,并在dotnetfiddle将JSON对象反序列化为类
这里被测试的The JSON的示例:
{
"`LCA0001": {
"23225007190002": "1",
"23249206670003": "1",
"01365100070018": "5"
},
"`LCA0003": {
"23331406670018": "1",
"24942506670004": "1"
},
"`LCA0005": {
"01365100070018": "19"
}
}
我想使用此代码:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
string json = "{\"`LCA0001\": {\"23225007190002\": \"1\",\"23249206670003\": \"1\",\"01365100070018\": \"5\"},\"`LCA0003\": {\"23331406670018\": \"1\",\"24942506670004\": \"1\"},\"`LCA0005\": {\"01365100070018\": \"19\"}}";
Console.WriteLine(json);
Console.WriteLine();
//This works
Console.Write("Deserialize without class");
var root = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, int>>>(json);
foreach (var locationKvp in root)
{
foreach (var skuKvp in locationKvp.Value)
{
Console.WriteLine("location: " + locationKvp.Key + ", sku: " + skuKvp.Key + ", qty: " + skuKvp.Value);
}
}
//Why doesn't this work?
Console.Write("\nDeserialize with class");
var root2 = JsonConvert.DeserializeObject<InventoryLocations>(json);
foreach (var locationKvp in root2.InventoryLocation)
{
foreach (var skuKvp in locationKvp.Value)
{
Console.WriteLine("location: " + locationKvp.Key + ", sku: " + skuKvp.Key + ", qty: " + skuKvp.Value);
}
}
}
}
class InventoryLocations
{
public Dictionary<Location, Dictionary<Sku, Qty>> InventoryLocation { get; set; }
}
public class Location
{
public string location { get; set; }
}
public class Sku
{
public string sku { get; set; }
}
public class Qty
{
public int qty { get; set; }
}
为什么反序列化成一个类是不行的?我只是不正确地定义类?
我在这里看到两个问题:一个是使用类作为字典键--JSON在那里有简单的字符串(并且不能有其他任何东西),所以这是行不通的。
的第二个问题是JSON的反序列化类的工作原理是匹配键的属性 - 所以它转换像
{
"prop1": "value1",
"prop2": "value2"
}
到的实例:
public class MyClass {
public string prop1 { get; set; }
public string prop2 { get; set; }
}
你的情况,这不能因为在你的JSON中所有的键都不是有效的属性名称。您必须坚持反序列化到字典
啊,这就是我没有理解的,它会工作吗?谢谢澄清。 – jared
从JSON生成类的方法之一是使用Visual Studio。
导航至Edit -> Paste Special -> Paste JSON As Classes
。对于发布的JSON,将生成以下类。
public class Rootobject
{
public LCA0001 LCA0001 { get; set; }
public LCA0003 LCA0003 { get; set; }
public LCA0005 LCA0005 { get; set; }
}
public class LCA0001
{
public string _23225007190002 { get; set; }
public string _23249206670003 { get; set; }
public string _01365100070018 { get; set; }
}
public class LCA0003
{
public string _23331406670018 { get; set; }
public string _24942506670004 { get; set; }
}
public class LCA0005
{
public string _01365100070018 { get; set; }
}
除了与MIMO的回答,您可以使用ContractResolver序列化类中化/解词典。
Here's a working example of your code in dotnetfiddle.
注意序列化的Json合同解析器是比原来的JSON不同。它必须使用这个合约解析器序列化,以便反序列化它。
如果您需要更多的解释,我从this StackOverflow question中提取合同解析器。
你是因为他们不是相同的反序列化? ('Dictionary >>'与使用类替换字符串(您的JSON与之不匹配) –
crashmstr
看起来像第二个示例(不起作用的示例)嵌套在更深的一层在你的第一个例子中,如果你反序列化为字典>而不是字典>? –