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)
...