繁体   English   中英

如何反序列化具有多种数据类型的 json 数组?

[英]How to deserialize a json array with multiple data types?

我现在需要反序列化一个看起来像这样的 JSON:

{
    "arguments": {
        "game": [
            "--username",
            "--version",
            "--assetsDir",
            {
                "rules": [
                    {
                        "action": "allow",
                        "features": {
                            "is_demo_user": true
                        }
                    }
                ],
                "value": "--demo"
            },
            {
                "rules": [
                    {
                        "action": "allow",
                        "features": {
                            "has_custom_resolution": true
                        }
                    }
                ],
                "value": [
                    "--width",
                    "--height"
                ]
            }
        ]
    }
}

如您所见,名为“game”的数组中同时包含“value”和“object”。 (但事实比这个例子更糟糕,元素的数量是不确定的)

arguments.game[*].value的数据类型也不确定

我以前用类来描述它,但是反序列化失败了。

似乎无法用 class 描述具有多种元素类型的数组?

我正在使用 Json.NET。 有没有办法反序列化这个“游戏”数组。

谢谢。

是否需要反序列化为 class 的实例? 您可以使用 ExpandoObject:

using System.Dynamic;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

Console.WriteLine("Hello, World!");
string json = @"{
""arguments"": {
    ""game"": [
        ""--username"",
        ""--version"",
        ""--assetsDir"",
        {
            ""rules"": [
                {
                    ""action"": ""allow"",
                    ""features"": {
                        ""is_demo_user"": true
                    }
                }
            ],
            ""value"": ""--demo""
        },
        {
            ""rules"": [
                {
                    ""action"": ""allow"",
                    ""features"": {
                        ""has_custom_resolution"": true
                    }
                }
            ],
            ""value"": [
                ""--width"",
                ""--height""
            ]
        }
    ]
}
}";

var expConverter = new ExpandoObjectConverter();
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(json, expConverter);

obj变量将包含JSON转换的结果,然后可以在代码中遍历动态object。

例如,要获取“游戏”下的字符串列表:

IList<object> list = new List<object>(obj.arguments.game);
foreach (object str in list)
{
    if (str as string != null)
    {
        Console.WriteLine(str as string);
    }
}

暂无
暂无

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

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