gkeenley
gkeenley

Reputation: 7388

How to make JsonConvert.DeserializeObject<T>() parse array when I won't always be passing array to it?

I have a method in my ASP.Net app that looks like this:

Method1<T>(String inputString)
{
  return JsonConvert.DeserializeObject<T>(inputString);
}

I pass stringified objects to Method1, and one of them is a stringified version of this object:

obj1: {
  a: ...
  b: [...]
}

ie. obj1 is an object that has an array as a property. Now, as is, JsonConvert.DeserializeObject<T>(inputString) won't parse the array part of this object. I learned from this post that I could make this work if type1 were the type of obj1 and I did JsonConvert.DeserializeObject<type1>(inputString). The problem is that I'll be passing stringified versions of a variety of different types of objects to Method1, so I don't know how else to do it than with <T>.

Does anyone know how I can approach this?

Upvotes: 2

Views: 79

Answers (1)

Neil
Neil

Reputation: 1633

Newtonsoft.Json.Linq api is great for this kind of scenario. You can parse your json into an abstract JToken object, and look at the token type to determine how to extract your array.

public MyType[] GetArrayFromJson(string json)
{
    var token = JToken.Parse(json);

    if (token.Type == JTokenType.Array)
    {
        return token.ToObject<MyType[]>();
    }
    else if(token.Type == JTokenType.Object)
    {
        return token["arrayPropName"].ToObject<MyType[]>();
    }
}

Upvotes: 1

Related Questions