使用ReadAsAsync< T>()反序列化复杂的Json对象 [英] Using ReadAsAsync<T>() to deserialize complex Json object
问题描述
我想在带有.net 4.0的mvc项目中使用ReadAsAsync()。结果为空。
I want to use ReadAsAsync() in my mvc project with .net 4.0. The result comes as null.
如果我输入uri到地址栏,则以chrome as(标记名已更改)为结果。
If I enter the uri to address bar, the result in chrome as(tag names are changed):
<ns2:MyListResponse xmlns:ns2="blablabla">
<customerSessionId>xxcustomerSessionIdxx</customerSessionId>
<numberOfRecordsRequested>0</numberOfRecordsRequested>
<moreResultsAvailable>false</moreResultsAvailable>
<MyList size="1" activePropertyCount="1">
<MySummary order="0">
<id>1234</id>
<name>...</name>
.
.
</MySummary>
</MyList>
</ns2:MyListResponse>
如果我在代码中使用以下语句:
If I use the statement in code :
using (var client = new HttpClient())
{
var response = client.GetAsync(apiUri).Result;
var message = response.Content.ReadAsStringAsync().Result;
var result1 = JsonConvert.DeserializeObject<MyListResponse>(message);
var result2 = response.Content.ReadAsAsync<MyListResponse>().Result;
}
消息以字符串格式显示为 {\ \ MyListResponse\:{\ customerSessionId\ ...}
对应于一个json对象,如下:
the message comes in string format as "{\"MyListResponse\":{\"customerSessionId\"...}"
which corresponds to a json object as:
{"MyListResponse":
{"customerSessionId":"xxcustomerSessionIdxx",
"numberOfRecordsRequested":0,
"moreResultsAvailable":false,
"MyList":
{"@size":"1",
"@activePropertyCount":"1",
"MySummary":
{"@order":"0",
"id":1234,
"name":"...",
.
.
}
}
}
}
,result1和result2的属性为null或默认值。类定义如下。我想将内容作为对象读取,但不能。您对解决这个问题有何建议?我究竟做错了什么?
and the properties of result1 and result2 came as null or default values. Class definitions are below. I want to read the content as an object but I couldn't. What do you advice to solve this? What am I doing wrong? Thanks in advance.
public class MySummary
{
public int @Order { get; set; }
public string Id { get; set; }
public string Name { get; set; }
.
.
}
public class MyList
{
public int @Size { get; set; }
public int @ActivePropertyCount { get; set; }
public MySummary MySummary{ get; set; }
}
public class MyListResponse
{
public string CustomerSessionId { get; set; }
public int NumberOfRecordsRequested { get; set; }
public bool MoreResultsAvailable { get; set; }
public MyList MyList { get; set; }
}
推荐答案
我定义了一个新类如:
public class ResponseWrapper
{
public MyListResponse MyListResponse { get; set; }
}
然后我将此包装与
var result1 = JsonConvert.DeserializeObject<ResponseWrapper>(message);
var result2 = response.Content.ReadAsAsync<ResponseWrapper>().Result;
然后它起作用了。我只需要MySummary对象,但我应该编写更多的类来使其工作。
then it worked. I need only MySummary object but I should write more classes to make it work.
这篇关于使用ReadAsAsync< T>()反序列化复杂的Json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!