gpt4 book ai didi

c# - 将 JSON 对象反序列化为类

转载 作者:行者123 更新时间:2023-11-30 20:38:12 25 4
gpt4 key购买 nike

我在将 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; }
}

反序列化为类不起作用是否有原因?我只是错误地定义了类吗?

最佳答案

我在这里看到两个问题:一个是使用类作为字典键 - JSON 那里只有简单的字符串(实际上不能有任何其他内容),所以这行不通。

第二个问题是,将 JSON 反序列化为类是通过将键与属性进行匹配来实现的——所以它会转换类似的东西

{
"prop1": "value1",
"prop2": "value2"
}

一个实例:

public class MyClass {
public string prop1 { get; set; }
public string prop2 { get; set; }
}

在您的情况下,这是行不通的,因为在您的 JSON 中,所有键都不是有效的属性名称。你必须坚持反序列化到字典

关于c# - 将 JSON 对象反序列化为类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35347698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com