我在將一個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; }
}
爲什麼反序列化成一個類是不行的?我只是不正確地定義類?
你是因爲他們不是相同的反序列化? ('Dictionary >>'與使用類替換字符串(您的JSON與之不匹配) –
crashmstr
看起來像第二個示例(不起作用的示例)嵌套在更深的一層在你的第一個例子中,如果你反序列化爲字典<位置,字典>而不是字典<字符串,字典>? –