All,
I am using the JsonConverter as explained here: How to handle both a single item and an array for the same property using JSON.net
It works fine if the element is an array and it has more than 1 record, or if it is empty ([]). However, when the element has a single record, I run into a parsing error: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List. to deserialize correctly.\r\nTo 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
My classes as such:
public class Qualifier
{
public string key { get; set; }
public string message { get; set; }
}
public class Qualifiers
{
public List<Qualifier> qualifier { get; set; }
}
public class Response
{
[JsonProperty("qualifiers", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(SingleOrArrayConverter<Qualifiers>))]
public List<Qualifiers> qualifiers { get; set; }
}
And below the JsonConverter:
public class SingleOrArrayConverter<T> : JsonConverter
{
public override bool CanConvert(Type objecType)
{
return (objecType == typeof(List<T>));
}
public override object ReadJson(JsonReader reader, Type objecType, object existingValue,
JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
if (token.Type == JTokenType.Array)
{
return token.ToObject<List<T>>();
}
return new List<T> { token.ToObject<T>() };
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
This is data that is throwing an error:
{
"response": {
"qualifiers": {
"qualifier": {
"key": "does.not.match",
"message": "Data Does Not Match"
}
}
}
}
Is there anything else I need to be doing to fix the single record error? Thanks in advance!