json字符串的反序列化返回空值

时间:2012-04-23 16:24:09

标签: c# asp.net json javascriptserializer

这是JSON字符串 -

“{\” 身体\ “:[\” VAL1 \ “\ ”VAL2 \“],\ ”头\“:{\ ”结果\“:真,\ ”时间\“:3.859}}”

这些是我的班级 -

[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; }
}

和代码 -

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

生成的ResponseHead对象具有值:

result: false 
time: 0.0 

无法正确映射值,但我不确定原因。 ResponseBody值正确输入。

请帮忙!

1 个答案:

答案 0 :(得分:3)

看起来您正在尝试阅读ResponseObj(您的JSON中的顶级对象),但编码为ResponseHead。以下应该工作:

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