1

I have some JSON that has an INT result, that may return as a single INT, or a LIST of INT's.. ie:

"ErrorCode":[3]

or

"ErrorCode": 1

How do I get that to deserialize with Newstonsoft.Json's JsonConvert?

If I define the object as a LIST, it fails when the results is a single INT, and vice versa.

Joe Kuzma
  • 13
  • 2
  • Try deserializing the ErrorCode value into a object and inspect the result (ie. make the ErrorCode property a property of type `object`). – Lasse V. Karlsen Apr 03 '17 at 20:10

3 Answers3

2

I would think you would need to settle on the data type for your json. Perhaps always have it return an array so that there is never just an INT. So, your json would look like this:

"ErrorCode":[3]

Then any single error code would just be an array of size 1.

JasonKretzer
  • 192
  • 1
  • 11
  • 1
    Unfortunately, I don't have much control over the results from the web service. So I can't change that. – Joe Kuzma Apr 03 '17 at 20:25
  • For the time being, I omitted the ErrorCode in the object... as the information isn't that important in my use of it... and it works. – Joe Kuzma Apr 03 '17 at 20:28
0

You can create a class like:

class MyResult {
    public object ErrorCode {get; set;}
}

And use it to deserialize your json:

MyResult r = JsonConvert.Deserialize<MyResult>(json);
List<int> errorCodes;
if (r.ErrorCode is JArray) {
    errorCodes = (r.ErrorCode as JArray).ToObject<List<int>>();
   // ...
} else {
   errorCodes = new List<int> { Convert.ToInt32(r.ErrorCode) };
   // ...
}

Hope it helps.

dcg
  • 4,187
  • 1
  • 18
  • 32
0

You can create a custom json convertor :

class ResolveListConverter<T> : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        List<T> list = new List<T>();
        if (reader.TokenType == JsonToken.StartArray)
        {
            reader.Read();
            while (reader.Value != null)
            {
                list.Add(Converter(reader.Value));
                reader.Read();
            }
        }
        else if(reader.Value != null)
        {
            list.Add(Converter(reader.Value));
        }
        return list;
    }

    public T Converter(object obj) => (T)Convert.ChangeType(obj, typeof(T));

    public override bool CanConvert(Type objectType) => true;
}

then you can deserialize your json :

var result = JsonConvert.DeserializeObject<List<int>>(json, new ResolveListConverter<int>());