Here are the basic classes:
public class Test
{
public Blabla blabla { get; set; }
}
public class Blabla
{
public string _score { get; set; }
public string _ref { get; set; }
[JsonConverter(typeof(FooConverter))]
public Foo[] foo { get; set; }
}
public class Foo
{
public string _colour { get; set; }
public string _ref { get; set; }
}
Set type of foo to be Foo[] no matter what the data is, and add [JsonConverter(typeof(FooConverter))] to use a custom converter.
Here is the custom converter:
public class FooConverter : JsonConverter
{
// Declared as abstract in JsonConverter so must be overridden
public override bool CanConvert(Type objectType) { return true; }
// Declared as abstract in JsonConverter so must be overridden
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
return token.Type == JToken.Array ? token.ToObject<Foo[]>() : new Foo[] { token.ToObject<Foo>() };
}
}
In the ReadJson method we load the data in a token and we check whether the data is an array or a plain object. If it is already an array we just return the array object as Foo[] and if it is a plain object we return a new Foo[] containing our plain object.
Here is a test case:
string json1 = @"{
""blabla"":
{
""_score"": ""1"",
""_ref"": ""50"",
""foo"":
{
""_colour"": ""Yellow"",
""_ref"": ""y50""
}
}
}";
string json2 = @"{
""blabla"":
{
""_score"": ""1"",
""_ref"": ""50"",
""foo"":
[
{
""_colour"": ""Yellow"",
""_ref"": ""y50""
},
{
""_colour"": ""Green"",
""_ref"": ""g50""
},
{
""_colour"": ""Red"",
""_ref"": ""r50""
}
]
}
}";
Test test1 = JsonConvert.DeserializeObject<Test>(json1);
Test test2 = JsonConvert.DeserializeObject<Test>(json2);
You will always have an array but there will be 1 element in the first test case, and 3 elements in the second test case.
blablaclass would have aFoo[]property and you'd use the custom converter to examine thefooproperty and populate the array.