繁体   English   中英

将具有可变属性的JSON对象解析为强类型对象

[英]Parsing JSON Object with variable properties into strongly typed object

{
"Profile": {
    "dProperty1": {
        "a": "value",
        "b": "value",
        "c": "value",
        "d": "value",
        "e": "value"
    },
    "dProperty2": {
        "a": "value",
        "b": "value",
        "d": "value",
        "e": "value"
    },
    "dProperty3": {
        "a": "value",
        "b": "value",
        "d": "value",
        "e": "value"
       }
    }
}

我有一个JSON对象,它可以具有任意数量的动态属性。 所有属性都是主要由相同字段组成的对象。 如何在C#中将此JSON解析为强类型对象?

如果您必须具有强类型化的结果,我会将反序列化为属性叠加字典

class AbscdeClass
{
    public string A { get; set; }
    public string B { get; set; }
    public string C { get; set; }
    public string D { get; set; }
    public string E { get; set; }
}

class JsonBody
{
    public Dictionary<string, AbscdeClass> Profile { get; set; }
}

并将原始JSON文本解析为

JsonBody json = JsonConvert.DeserializeObject<JsonBody>(jsonString);

我将整个树解析为JObject ,然后在适当的子对象上调用ToObject<> 样例代码:

using System;
using System.IO;
using System.Linq;
using Newtonsoft.Json.Linq;

class Example
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var json = File.ReadAllText("test.json");
        var root = JObject.Parse(json);        
        var profile = (JObject) root["Profile"];
        var map = profile.Properties()
                         .ToDictionary(p => p.Name, p => p.Value.ToObject<Example>());
        foreach (var entry in map)
        {
            Console.WriteLine($"Key: {entry.Key}; Name: {entry.Value.Name}; Age: {entry.Value.Age}");
        }
    }
}

JSON:

{
  "Profile": {
    "dProperty1": {
      "name": "First",
      "age": 30,
      "extra": "Ignored"
    },
    "dProperty2": {
      "name": "Second",
      "age": 25
    },
    "dProperty3": {
      "name": "Third",
      "age": 50
    }
  }
}

结果:

Key: dProperty1; Name: First; Age: 30
Key: dProperty2; Name: Second; Age: 25
Key: dProperty3; Name: Third; Age: 50

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM