Home > front end >  How to deserialize a json array with multiple data types?
How to deserialize a json array with multiple data types?

Time:09-26

I now need to deserialize a JSON that looks like this:

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

As you can see, the array named "game" has both "value" and "object" in it. (But the fact is WORSE than this example, the number of elements is NOT certain)

And the data type of arguments.game[*].value is NOT certain, too.

I used to use classes to describe it, but deserialization failed.

Can't seem to describe an array with multiple element types with a class?

I am using Json.NET. Is there any way to deserialize this "game" array.

Thanks.

CodePudding user response:

Is it a requirement to deserialize to an instance of a class? You could use an 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);

The obj variable will contain the result of the JSON conversion, then you can traverse the dynamic object in code.

For example, to get a list of strings under 'game':

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