rcs
rcs

Reputation: 7197

JsonReader how to handle single item vs array

I'm using JSON .NET to parse the response that I receive from webservice. The problem is that the response may contain single item, or multiple items(array), which will cause the response string to be slightly different.

Single item response:

{
    "row": "1",
    "name": "John"
}

Multiple items response:

[
    {
        "row": "1",
        "name": "John"
    },
    {
        "row": "2",
        "name": "Doe"
    },
]

I'm using the following code to parse

 List<MyClass> wsRetrieveDataResponse = JsonReadSerializer.Deserialize<List<MyClass>>(reader);

The problem here is that since it is using List<MyClass>, it is expecting an array, and if the web service response is a single item, it will throw an error. How do I handle both cases?

[EDIT]: JsonReadSerializer has the type of JsonSerializer, which is part of JSON.NET. Deserialize is JSON.NET function. I just add some constructor to handle some cases. Code as below.

public static JsonSerializer JsonReadSerializer;

Constructor for JsonReadSerializer

JsonReadSerializer = new JsonSerializer()
{
    MissingMemberHandling = JSON_ENFORCE_MISSING ? MissingMemberHandling.Error : MissingMemberHandling.Ignore,
    NullValueHandling = JSON_NULL_IGNORE ? NullValueHandling.Ignore : NullValueHandling.Include
 };

[EDIT #2]: My response is using type JsonTextReader

// Get the response.  
...
WebResponse response = webRequest.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);

return new JsonTextReader(reader);

Upvotes: 2

Views: 1474

Answers (2)

er-sho
er-sho

Reputation: 9771

You can check the type of your json with JTokenType enum provided by Newtonsoft.Json.Linq

First of all try to load your JToken with JsonTextReader with .Load method provided by JToken and then check if parsed JToken is an Array or Object.

After that JToken.ToObject<> cast or map JToken to specified type that you want to.

JToken jToken = JToken.Load(reader);

if (jToken.Type == JTokenType.Array)
{
    List<MyClass> wsRetrieveDataResponse = jToken.ToObject<List<MyClass>>();
}
else if (jToken.Type == JTokenType.Object)
{
    MyClass wsRetrieveDataResponse = jToken.ToObject<MyClass>();
}

Upvotes: 3

Jinish
Jinish

Reputation: 2073

You could use something of this sort:

var token = JToken.Parse(content);

if (token is JArray)
{
    IEnumerable<MyClass> response= token.ToObject<List<MyClass>>();
}
else if (token is JObject)
{
    MyClass myClass= token.ToObject<MyClass>();
}

Upvotes: 4

Related Questions