I have a 5 objects nested json file. In nutshell, the json file has the following pattern:
{
"Object1": {
"Object2": {
"Object3": {
"Object4": [
"Object5",
"Object5",
"Object5"
]
}
}
}
}
Edit: Previously I had inconsistent naming. I have revised the names to reflect the comments that I was given.
I would like to deserialize the json into a C# object as follows
using System;
using Newtonsoft.Json;
namespace Example
{
class Program
{
public class Object1
{
public string Name { get; set; }
public Object2[] Object2s { get; set; }
}
public sealed class Object2
{
public string Name { get; set; }
public Object3[] Object3s { get; set; }
}
public class Object3
{
public string Name { get; set; }
public Object4 [] Object4s { get; set; }
}
public class Object4
{
public string Name { get; set; }
public Object5 [] Object5s { get; set; }
}
public class Object5
{
public string Name { get; set; }
}
static void Main(string[] args)
{
string json = "{ \"Object1\": { \"Object2\": { \"Object3\": { \"Object4\": [ \"Value1\",\"Value2\",\"Value3\" ] } }}}";
Object1[] object1s = JsonConvert.DeserializeObject<Object1[]>(json);
Console.WriteLine(object1s[0].Name);
}
}
}
Unfortunately, when I run it, it results in the following exception:
Newtonsoft.Json.JsonSerializationException
HResult=0x80131500
Message=Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'Example.Program+Object1[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'Object1', line 1, position 15.
Is there any way this can be achieved without resorting to looping through the json tree?