2

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?

Glenn Ferrie
  • 10,290
  • 3
  • 42
  • 73
gkeenley
  • 6,088
  • 8
  • 54
  • 129
  • Are you experiencing an exception when you run your code? If you feel constrained by the C# type system, you can use `dynamic`... see this other post. https://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object – Glenn Ferrie Mar 25 '20 at 03:46

1 Answers1

1

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[]>();
    }
}
Neil
  • 1,613
  • 1
  • 16
  • 18
  • Hi Neil, thanks for your reply. I've parsed my input string as a JToken, I'm not sure what to do with that JToken though. It looks like in your code, you're checking if the JToken itself is an array, or if it just contains an array, and returning the array in either case. What I want to do is just return the object itself, whether or not it contains an array. Do you know how to do that? – gkeenley Mar 25 '20 at 05:16
  • @gkeenley Sounds like you might have an [xy problem](http://xyproblem.info/). Your existing method is for deserializing objects, but if I understand correctly your object types don't all define this array property (but the array will still exist within your json). You should probably just create a separate method for extracting your array when needed. No need to hack at a 1 line method to try reusing it. Let me know if I'm misunderstanding – Neil Mar 25 '20 at 15:48