如何使用 Newton Soft 为嵌套对象解析此 JSON

How to parse this JSON using Newton Soft for nested object

如何解析这个 JSON

使用 Newton Soft

我试过了,但给了我空值,因为我的模态应该有 class 1, 2, 3 ... 但这是动态的。所以变得混乱。

感谢您的帮助!

{
"data": {
    "1": {
        "test": {
            "col1": "123",
            "col2": "name"
        }
    },
    "2": {
        "test": {
            "col1": "345",
            "col2": "name2"
        }
    },
    "3": {
        "test": {
            "col1": "456",
            "col2": "name3"
        }
    }
}
class root 
{ 
    data data{get; set;};
}

class data
{ 
    List<object> innerObject {get; set;} //not sure as labels are dynamic 
} 

class test
{ 
    col1{get; set;} 
    col2{get; set;} 
} //Calling it in that way .. 

root r = JsonConvert.DeserializeObject<root>(result);

您可以使用字典来解析具有自定义 属性 名称的 JSON 对象:

public class Test
{
    public string col1 { get; set; }
    public string col2 { get; set; }
}

public class DataValue
{
    public Test test { get; set; }
}

public class RootObject
{
    public RootObject() { this.data = new Dictionary<string, DataValue>(); }
    public Dictionary<string, DataValue> data { get; set; }
}

Deserialize a Dictionary

如果您确定字典键总是数字,您可以使用整数键,并使用SortedDictionay对值进行排序:

public class RootObject
{
    public RootObject() { this.data = new SortedDictionary<long, DataValue>(); }
    public SortedDictionary<long, DataValue> data { get; set; }
}

是一个不错的选择,但您还有一些其他选择:

  1. 如果您可以控制正在生成的 JSON,请尽可能使用数组让您的生活更轻松。看起来你真正想要的是这个:

    {
        "data": [{
            "test": {
                "col1": "123",
                "col2": "name"
            }, {
            "test": {
                "col1": "345",
                "col2": "name2"
            }, /* etc */
        ]
    }
    

    这样,data 表示一个数组,您可以这样反序列化它:

    class Root 
    { 
        List<Data> Data  { get; set; };
    }
    
    class Data
    {
        Test Test { get; set; }
    }
    
    JsonConvert.DeserializeObject<Root>(json);
    
  2. 您可以使用自定义转换器将 JSON 强制转换为数组结构。这是对您的 JSON 做出了很多假设。例如,假设您有一个带有整数键的对象,数字之间没有空格:

    public class ObjectAsArrayConverter : JsonConverter 
    {
      public override bool CanConvert(Type type)
      {         
        return
          type.IsGenericType &&
          typeof(List<>) == type.GetGenericTypeDefinition() &&
          typeof(Data) == type.GetGenericArguments()[0];
      }
    
      public override object ReadJson(
        JsonReader reader,
        Type objectType,
        object existingValue,
        JsonSerializer serializer)
      {
        JObject obj = JObject.ReadFrom(reader).ToObject<JObject>();
    
        return obj.Properties()
          .Select(p => new { Index = int.Parse(p.Name), Value = obj[p.Name].ToObject<Data>() })
          .OrderBy(p => p.Index)
          .Select(p => p.Value)
          .ToList();
      }
    
      public override void WriteJson(
        JsonWriter writer,
        object value,
        JsonSerializer serializer)
      {
        throw new NotImplementedException();
      }
    
    }
    

    这将允许您将 JSON 反序列化为以下结构:

    class Root 
    { 
        public List<Data> Data {get; set;}
    }
    
    class Data
    {
        public Test Test { get; set; }
    }
    
    class Test
    { 
        public string Col1 {get; set;} 
        public string Col2 {get; set;}
    }
    

    示例: https://dotnetfiddle.net/e2Df7h

您可能需要调整第二个建议,例如,如果您希望数组是稀疏的,您可能希望让代码期望它。