Approach for parsing json string with different type of objects

562 views Asked by At

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.

** How can I parse this json by specifying Result type.** I am using JSONFx.net for deserializing back to objects.

Thanks

1

There are 1 answers

0
Sai On

Classes generated from your JSON data:

public class Result
{
    public List<string> sample1 { get; set; }
    public string sample2 { get; set; }
}

public class Datum
{
    public int key { get; set; }
    public Result result { get; set; }
}

    public class RootObject
    {
    public string serverTime { get; set; }
    public List<Datum> data { get; set; }
}

User Newtonsoft.Json dll to Deserialize JSON data like:

var obj = JsonConvert.DeserializeObject<RootObject>("yourjsonstring");

then you can use properties of obj like:

var date = DateTime.Parse(obj.serverTime);

and so on.