Assuming that the property names inside the "propertyNames"
object are all integers, you can define your data model as follows, using ListToDictionaryConverter<T>
from this answer to Display JSON object array in datagridview:
The data model:
public class MyObject
{
public string a { get; set; }
public string b { get; set; }
public string z { get; set; }
}
public class Datum
{
[JsonConverter(typeof(ListToDictionaryConverter<MyObject>))]
public List<MyObject> propertyNames { get; set; }
public string otherProperty { get; set; }
}
public class RootObject
{
public List<Datum> data { get; set; }
}
The converter is copied as-is with no modification. It transforms the JSON object
{
"1":{
"a":"a1",
"b":"b1",
"z":"z1"
},
"2":{
"a":"a2",
"b":"b2",
"z":"z2"
}
}
into a List<MyObject>
with values at indices 1 and 2, and null
at index zero.
Demo fiddle #1 here.
Alternatively, if you would prefer your propertyNames
to be of type Dictionary<int, MyObject>
, you can modify the model and converter as follows:
public class Datum
{
[JsonConverter(typeof(IntegerDictionaryToListConverter<MyObject>))]
public Dictionary<int, MyObject> propertyNames { get; set; }
public string otherProperty { get; set; }
}
public class IntegerDictionaryToListConverter<T> : JsonConverter where T : class
{
// From this answer https://stackoverflow.com/a/41559688/3744182
// To https://stackoverflow.com/questions/41553379/display-json-object-array-in-datagridview
public override bool CanConvert(Type objectType)
{
return typeof(Dictionary<int, T>).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var dictionary = existingValue as IDictionary<int, T> ?? (IDictionary<int, T>)serializer.ContractResolver.ResolveContract(objectType).DefaultCreator();
if (reader.TokenType == JsonToken.StartObject)
serializer.Populate(reader, dictionary);
else if (reader.TokenType == JsonToken.StartArray)
{
var list = serializer.Deserialize<List<T>>(reader);
for (int i = 0; i < list.Count; i++)
dictionary.Add(i, list[i]);
}
else
{
throw new JsonSerializationException(string.Format("Invalid token {0}", reader.TokenType));
}
return dictionary;
}
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Demo fiddle #2 here.
If the property names aren't always integers you can modify the converter slightly to deserialize to a Dictionary<string, T>
.