-1

I'm trying to parse a section of a json document using System.Text.Json in C# (.NET 6). I have used the following to grab the relevant section from the api response:

string jsonString = await httpClient.GetStringAsync(url);
string fieldsetJsonString = JsonDocument.Parse(jsonString).RootElement.GetProperty("page-content").GetProperty("dialog").GetProperty("content").GetProperty("fieldset").ToString();

I'm left with a string that contains the following structure, where the key/value pairs within "combo","text",etc keys are completely variable, and even those higher level keys are optional:

[
 {
    "order": 1,
    "combo": [
        {
            "random_string": "random",
            "random_bool": true,
            "random_int": 1,
            "random_list": [
                {
                    "random_string1": "ABC"
                },
                {
                    "random_string2": "DEF"
                }
            ]
        },
        {
            "random_string": "random",
            "random_bool": true,
            "random_int": 1
        }
    ]
},
{
    "order": 2,
    "text": [
        {
            "random_string": "random",
            "random_bool": true,
            "random_int": 1
        },
        {
            "random_string": "random",
            "random_bool": true,
            "random_int": 1
        },
        {
            "random_string": "random",
            "random_bool": true,
            "random_int": 1,
            "random_object": {
                "key1": "TEXT",
                "key2": true
            }
        }
    ],
    "combo": [
        {
            "random_string": "random",
            "random_bool": true,
            "random_int": 1,
            "random_list": [
                {
                    "random_string1": "ABC"
                },
                {
                    "random_string2": "DEF"
                }
            ]
        },
        {
            "random_string": "random",
            "random_bool": true,
            "random_int": 1
        },
        {
            "random_string": "random",
            "random_bool": true,
            "random_int": 1,
            "random_list": [
                {
                    "random_string1": "ABC"
                },
                {
                    "random_string2": "DEF"
                }
            ]
        }
    ],
    "comment": [
        {
            "random_string": "random",
            "random_bool": true,
            "random_int": 1
        },
        {
            "random_string": "random",
            "random_bool": true,
            "random_int": 1
        }
    ],
    "boolean": [
        {
            "random_string": "random",
            "random_bool": true,
            "random_int": 1
        },
        {
            "random_string": "random",
            "random_bool": true,
            "random_int": 1
        }
    ]
 }
]

I've tried to deserialize using the following model:

public class Root
{
    public List<Item> fieldset { get; set; }
}
public class Item
{
    public Dictionary<string, object> item { get; set; } = new Dictionary<string, object>();
}

var mymodel = JsonSerializer.Deserialize<Root>(fieldsetJsonString);

but I'm getting an error:

System.Text.Json.JsonException: The JSON value could not be converted to MySolution.Models.Root. Path: $ | LineNumber: 0 | BytePositionInLine: 1.
at System.Text.Json.ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType)
at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
...
trueimage
  • 309
  • 2
  • 4
  • 14
  • Assuming there's no rhyme or reason (like a header that tells you what the result is) then it will be a huge pain. It should be be a felony to abuse JSON this way. – Crowcoder Dec 08 '22 at 23:38
  • "I'm trying to parse a section of a json document " What section are you trying to parse? "GetProperty("page-content").GetProperty("dialog").GetProperty("content") " I can' t see any of these properties. Do you need some special data or any json string data? – Serge Dec 08 '22 at 23:41

1 Answers1

0

The first thing I notice is that your JSON starts with a [ and not {. The one trick to deserializing JSON is you want to start with an assumption about the root, is it an array or an object. In your case, an array, so you're going to deserialize into T[] or IEnumerable<T>.

var fieldSets = JsonSerializer.Deserialize<Dictionary<string, dynamic>[]>(fieldsetJsonString);

This will give you a list of dictionaries. The first will have the keys "order" and "combo", while the second has keys "order", text", "combo", etc.. The value for fieldSets[0]["order"] is going to be a JsonElement with the value of 1. The value for fieldSets[1]["combo"] is going to be a JsonElement with the value of an object as a JsonElement.

Depending on what you want to do next depends on whether JsonElement is the right object for you. If you want to traverse the JSON tree like XML, you might prefer Newtonsoft's Json.NET

AceGambit
  • 423
  • 3
  • 11