简体   繁体   中英

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

I have a JSON object, which can have any number of dynamic properties. All the properties are objects that consist of mostly of the same fields. How can i parse this JSON into a strongly typed object in C#?

If you must have strongly typed result I would deserialize Profile as a dictionary of superposition of properties

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

and parse original JSON text as

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

I would parse the whole tree as a JObject , and then call ToObject<> on appropriate sub-objects. Sample code:

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

Result:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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