neuDev33
neuDev33

Reputation: 1623

Deserialization of a json string returns null values

This is the JSON string -

"{\"body\":[\"VAL1\",\"VAL2\"],\"head\":{\"result\":true,\"time\":3.859}}"

These are my classes -

[Serializable]
public class ResponseHead
{               
    public bool result {get; set;}              
    public float time {get; set;}
}

[Serializable]
public class ResponseBody
{        
    public string[] body {get; set;}
}

[Serializable]
public class ResponseObj
{        
    public ResponseBody body {get; set;}
    public ResponseHead head { get; set; }
}

And the code -

JavaScriptSerializer serializer = new JavaScriptSerializer();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    responseText = streamReader.ReadToEnd();
}
ResponseObj response_obj = new ResponseObj();

ResponseHead rhead = new ResponseHead();
rhead = serializer.Deserialize<ResponseHead>(responseText); //not working

The resultant ResponseHead object has values:

result: false 
time: 0.0 

It is not able to map the values correctly, but i'm not sure why. The ResponseBody values are coming in correctly.

Please help!

Upvotes: 0

Views: 3920

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100547

Looks like you are trying to read ResponseObj (which is top level object in your JSON), but coded for ResponseHead. Following should work:

var wholeObject = serializer.Deserialize<ResponseObj>(responseText);
rhead = wholeObject.head;

Upvotes: 4

Related Questions