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);