【问题标题】:Deserializing nested JSON array inside nested JSON object in c#?在c#中的嵌套JSON对象内反序列化嵌套JSON数组?
【发布时间】:2020-04-30 17:20:54
【问题描述】:

我有一个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 和 ids

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 你的json有效吗?你的 json 是 {container:{can1:[...], ids:[...], can2:[...], ids:[...]}} ?
  • 这能回答你的问题吗? Deserialize JSON with C#

标签: c# json json-deserialization


【解决方案1】:

安装 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);

更新

根据评论,试试这个:

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; }
}

【讨论】:

  • 是什么阻止了你?
  • Json 字符串在运行时是动态的,有时里面会有两个 cans 数组有时可能根本没有 can 对象在这种情况下如何遍历动态 json 字符串并获取 cans 名称和值其他属性
  • 它工作得很好,非常感谢,我是 c# 新手,我不知道这个字典和数组,它对我帮助很大。
  • 我还有一个要求,容器也可能不同,可以有不同的容器,比如不同的罐子,包含相同的 json 结构在这种情况下如何迭代?
  • { "steelcontainer" : { "cans1" : [ { "name" : "Fav", "ids" : [ "1245","234" ] } ], "ids" : [ " 1211","11123122" ], "cans2" : [ { "name" : "sub1", "ids" : [ "123" ] } ], "ids" : [ "121","11123" ] }, " glasscontainer" : { "cans5" : [ { "name" : "sub", "ids" : [ "123" ] }] } }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-08
  • 1970-01-01
  • 2019-09-22
  • 2016-12-12
相关资源
最近更新 更多