I'm trying to deserialize json from 3rd-party service:
{
"route1":[
{
"Id":1
}
],
"route2":{
"error":"Id not found"
}
}
It's a Dictionary
, but value can be array or an object. I need the only array, so I decided to put an empty array when I found an object in JsonConverter
.
public class Item
{
public int Id { get; set; }
}
public class JsonInfo
{
[JsonConverter(typeof(ItemConverter))]
public List<Item> Items{ get; set; }
}
public class ItemConverter : Newtonsoft.Json.JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
switch (reader.TokenType)
{
case JsonToken.String:
case JsonToken.StartObject:
return new List<Item>();
case JsonToken.StartArray:
var array = JArray.Load(reader);
var data = array.Select(ParseValue).ToList();
return data;
default:
return null;
}
}
public override bool CanConvert(Type objectType)
{
return false;
}
private Item ParseValue(JToken value)
{
switch (value.Type)
{
case JTokenType.Object:
return value.ToObject<Item>();
default:
return null;
}
}
}
But when I'm trying to deserialize Dictionary<string, JsonInfo>
it raises an error (must be json array). I think the problem that converter trying to find JsonInfo
property in json, instead of array inside this class.
Maybe I missed something?
Do we have an attribute, that allows skipping property name?