Reputation: 1217
I receive data from a provider and it can look like:
{
"data": [
{
"propertyNames":[
{
"a":"a1",
"b":"b1",
...
"z":"z1"
},
{
"a":"a2",
"b":"b2",
...
"z":"z2"
},
],
...
"otherProperty": "abc"
},
{
"propertyNames":{
"1": {
"a":"a1",
"b":"b1",
...
"z":"z1"
},
"2": {
"a":"a2",
"b":"b2",
...
"z":"z2"
},
},
...
"otherProperty": "bce"
}
]
}
So effectively, propertyNames
can be the following types:
[JsonProperty("propertyNames")]
Dictionary<string, MyObject> PropertyNames {get;set;}
[JsonProperty("propertyNames")]
List<MyObject> PropertyNames {get;set;}
How can I deserialize this?
Upvotes: 1
Views: 75
Reputation: 11283
There are multiple choices really how you can approach this.
For example you can use JObject as a type
[JsonProperty("propertyNames")]
JObject PropertyNames {get;set;}
Unfortunately you would have to write down complex logic to parse information out of that.
You can also create custom JsonConverter
public class DynamicTypeConverter: JsonConverter<DynamicType>
{
public override void WriteJson(JsonWriter writer, Version value, JsonSerializer serializer)
{
}
public override DynamicType ReadJson(JsonReader reader, Type objectType, Version existingValue, bool hasExistingValue, JsonSerializer serializer)
{
var obj = new DynamicType();
// Least fun part, compute & assign values to properties
// Logic depends if you are going to use JObject.Load(reader) or reader.Read() with reader.Value and TokenType
return obj;
}
}
public class DynamicType
{
Dictionary<string, MyObject> PropertyNamesDict {get;set;}
List<MyObject> PropertyNamesList {get;set;}
}
Upvotes: 2
Reputation: 116786
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>
.
Upvotes: 2