【发布时间】:2016-02-11 18:55:21
【问题描述】:
我在将 JSON 对象反序列化为类(使用 JSON.NET)时遇到了一点麻烦,希望有人能指出我正确的方向。下面是我正在尝试的一段代码,并在dotnetfiddle进行测试
这是 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; }
}
反序列化为 Class 不起作用有什么原因吗?我只是错误地定义了类吗?
【问题讨论】:
-
你的因为它们反序列化不一样? (
Dictionary<string, Dictionary<string, int>>>与用类代替字符串(您的 JSON 与该字符串不匹配)。 -
看起来您的第二个示例(不起作用的示例)嵌套更深一层。在您的第一个示例中,如果您反序列化为 Dictionary
> 而不是 Dictionary > 会起作用吗?
标签: c# json.net json-deserialization