在 C# 中反序列化嵌套 JSON 对象内的嵌套 JSON 数组?

Deserializing nested JSON array inside nested JSON object in c#?

我有一个 json 文件如下:

{
  "container" : {
    "cans1" : 
    [
      {
        "name" : "sub",
        "ids" : 
        [
          "123"
        ]
      },
      {
        "name" : "Fav",
        "ids" : 
        [
          "1245","234"
        ]
      },
      {
        "name" : "test",
        "ids" : 
        [
          "DOC12","DOC1234"
        ]
      }
    ],
    "ids" : 
    [
      "1211","11123122"
    ],
"cans2" : 
    [
      {
        "name" : "sub1",
        "ids" : 
        [
          "123"
        ]
      }
     ],
     "ids" : 
    [
      "121","11123"
    ]

}

我想使用 c#

获取此 json 文件中每个罐头的名称值 sub、fav、test 和 id

安装 nuget Newtonsoft.Json。创建下一个层次结构:

using System;
using System.Collections.Generic;

using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

public class MyClass
{
    [JsonProperty("container")]
    public Container Container { get; set; }
}

public class Container
{
    [JsonProperty("cans1")]
    public Cans[] Cans1 { get; set; }

    [JsonProperty("ids")]
    [JsonConverter(typeof(DecodeArrayConverter))]
    public long[] Ids { get; set; }

    [JsonProperty("cans2")]
    public Cans[] Cans2 { get; set; }
}

public class Cans
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("ids")]
    public string[] Ids { get; set; }
}

然后

 JsonConvert.DeserializeObject<MyClass>(yourJsonString);

UPD

根据评论,试试这个:

var des = JsonConvert.DeserializeObject<MyClass>(t);

foreach(var arr in des.Container.Where(r => r.Key.StartsWith("cans")))
{

    Console.WriteLine($"{arr.Key}");
    foreach(var elem in arr.Value)
    {
        Console.WriteLine($"    {elem.Value<string>("name")}");
    }
}

public class MyClass
{
    [JsonProperty("container")]
    public Dictionary<string, JArray> Container { get; set; }
}