Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c#模型中不同对象数组的反序列化_C#_Json.net - Fatal编程技术网

c#模型中不同对象数组的反序列化

c#模型中不同对象数组的反序列化,c#,json.net,C#,Json.net,这是JSON,我想使用Newtonsoft.JSON将其映射到c#对象 { "PremiumStructure": [ { "Level": true, "LevelText": "Level" }, { "Stepped": false, "SteppedText": "Stepped" }, { "DifferentPropetyNameinFuture" : false,

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

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

}

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

只需使用以下方法即可。创建一个RootObj并将属性定义为
列表
,其中包含
字典

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


这给了我具体的生成模型,但在数组中,我可能有更多的对象,我将不得不添加更多的具体类,以根据JSON2Charp映射模型。所以,我想要一个通用的解决方案

然后,您可能不想反序列化JSON,而是将其解析为:

然后使用
root
的索引器访问不同的KVP。e、 g

root["PremiumStructure"][0]["Level"]
或者,如果要使用点表示法访问属性,请将JSON反序列化为
动态
变量,并使用该变量直接访问属性:

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

这给了我具体的生成模型,但在数组中,我可能有更多的对象,我将不得不添加更多的具体类,以根据JSON2Charp映射模型。所以,我想要一个通用的解决方案。这样我就不必改变模型,而需要增加数组中的对象。
root["PremiumStructure"][0]["Level"]
dynamic obj = JsonConvert.DeserializeObject(json);
obj.PremiumStructure[0].Level