如何在C#模型中反序列化不同对象的数组

时间:2018-12-23 08:23:21

标签: c# json.net

这是JSON,我想使用Newtonsoft.json将其映射到c#对象中

{
"PremiumStructure": [
    {
        "Level": true,
        "LevelText": "Level"
    },
    {
        "Stepped": false,
        "SteppedText": "Stepped"
    },
    {
    "DifferentPropetyNameinFuture" : false,
    "DifferentPropetyNameinFutureText" : "stringValue"
    }
    ]

}

3 个答案:

答案 0 :(得分:1)

只需使用以下方法。创建一个RootObj并将属性定义为python manage.py collectstatic ,其中包含List

Dictionary

输出:

class MyObj
{
    public List<Dictionary<string, object>> PremiumStructure;
}

class Program
{
    static void Main(string[] args)
    {
        var text = File.ReadAllText("test.json"); // the file contains your json example

        var myObj = JsonConvert.DeserializeObject<MyObj>(text);

        foreach (var item in myObj.PremiumStructure)
        {
            foreach (var key in item.Keys)
            {
                Console.WriteLine($"Key: {key} Value: {item[key]}");
            }
        }

        Console.ReadLine();
    }
}

enter image description here

答案 1 :(得分:0)

您可以使用json2csharp将其转换为C#类。

答案 2 :(得分:0)

  

这为我提供了具体的生成模型,但是在数组中我可能会有更多的对象,因此我将不得不添加更多具体的类以根据json2csharp映射模型。因此,我想要通用的解决方案。

然后,您可能不希望反序列化JSON,而只需将其解析为JObject

// Remember to add "using Newtonsoft.Json.Linq;"!
JObject root = new JObject.Parse(yourJSONString);

然后使用root的索引器访问不同的KVP。例如

root["PremiumStructure"][0]["Level"]

或者,如果要使用点符号访问属性,请将JSON反序列化为dynamic变量,然后直接使用该变量访问属性:

dynamic obj = JsonConvert.DeserializeObject(json);
obj.PremiumStructure[0].Level