简体   繁体   中英

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!

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM