如何将此 JSON 反序列化为 C# Class

How to deserialize this JSON to C# Class

我正在使用 returns 来自请求json 的 WebAPI

{
    "apps": {
        "570": {
            "228983": {
                "8124929965194586177": "available"
            },
            "228990": {
                "1829726630299308803": "available"
            },
            "373301": {
                "840315559245085162": "available"
            },
            "373302": {
                "688854584180787739": "available"
            },
            "373303": {
                "3675525977143063913": "available"
            },
            "373305": {
                "4435851250675935801": "available"
            },
            "381451": {
                "6984541794104259526": "available"
            },
            "381452": {
                "1442783997179322635": "available"
            },
            "381453": {
                "6878143993063907778": "available"
            },
            "381454": {
                "7824447308675043012": "available"
            },
            "381455": {
                "5681120743357195246": "available"
            }
        },
        "674940": {
            "674941": {
                "6246860772952658709": "available"
            }
        }
    }
}

它 returns 一个 AppID 列表(int),包含另一个 DepotID 列表,它包含一个 ManifestID(Key)以及它是否可用(Value)。

我想反序列化为 class 以便于使用它,但我无法想象如何去做。我是来自 C/C++

的 C# 新手

您可以使用 Json.NET which is a popular JSON library for C#. See Deserialize an Object.

示例:

public class MyData
{
    public Dictionary<long, Dictionary<long, Dictionary<long, string>>> apps { get; set; }
}

var data = JsonConvert.DeserializeObject<MyData>(json);

// Use 'data.apps'

您可以使用 Newtonsoft.Json NuGet 包并将您的数据反序列化为嵌套字典,如下所示:

var data = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, Dictionary<string, Dictionary<string, string>>>>>(File.ReadAllText("Data.json"));

为确保您获得正确的数据,您可以运行此代码打印出来:

foreach (var a in data) { Console.WriteLine(a.Key); foreach (var b in a.Value) { Console.WriteLine("\t" + b.Key); foreach (var c in b.Value) { Console.WriteLine("\t\t" + c.Key); foreach (var d in c.Value) { Console.WriteLine("\t\t\t" + d.Key + ": " + d.Value); } } } }

不太确定如何将此数据反序列化为 class,因为它没有太多妨碍 属性 名称...

我不确定将其建模为 C# 类 没有 属性 名称超出您 Json 的 "apps" 级别,但您 可以这样做:

使用以下 类 为您的 Json 建模:

public class AppIds : Dictionary<string, DepotId> { }
public class DepotId : Dictionary<string, ManifestId> { }
public class ManifestId : Dictionary<string, string> { }

然后你可以使用 Newtonsoft.Json

class Program
{
    static void Main(string[] args)
    {
        string jsonPath = @"c:\debug\data.json";
        System.IO.Stream s = new System.IO.FileStream(jsonPath,System.IO.FileMode.Open, System.IO.FileAccess.Read);

        AppIds data = JsonConvert.DeserializeObject<Dictionary<string, AppIds>>(File.ReadAllText(jsonPath))["apps"];
    }
}