Monday, 12 August 2013

Approach for parsing json string with different type of objects

Approach for parsing json string with different type of objects

I have following json string
{ "serverTime": "2013-08-12 02:45:55,558", "data": [ { "key1": 1,
"result": { "sample1": [ "" ], "sample2": "test2" } }, { "key1": 1,
"result": { "sample3": [ "" ], "sample4": "test2" } } ] }
Using JSONTOC#
Following classes are generated.
public class Result {
public List<string> sample1 { get; set; }
public string sample2 { get; set; }
public List<string> sample3 { get; set; }
public string sample4 { get; set; } }
public class Datum {
public int key1 { get; set; }
public Result result { get; set; } }
public class RootObject {
public string serverTime { get; set; }
public List<Datum> data { get; set; } }
As one can see the tool has generated Result class with all the possible
properties.
I am trying to following approach to parse the json
public class Response<T>
{
public Date serverTime;
public ResponseData<T>[] data;
}
public class ResponseDataBase
{
public int key1;
}
public class ResponseData<T> : ResponseDataBase
{
public T result;
}
Here can T be following two classes
Class Result1
{
public List<string> sample1 { get; set; }
public string sample2 { get; set; }
}
Class Result2
{
public List<string> sample3 { get; set; }
public string sample4 { get; set; }
}
I have these class declaration as reference, the class definition can be
totally different.
I am trying to parse this json by specifying Result type. I am using
JSONFx.net for deserializing back to objects.
Thanks

No comments:

Post a Comment