asp.net-mvc-4 - 使用 ReadAsAsync<T>() 反序列化复杂的 Json 对象

标签 asp.net-mvc-4 .net-4.0 httpclient

我想在 .net 4.0 的 mvc 项目中使用 ReadAsAsync()。结果为空。

如果我在地址栏输入 uri,chrome 中的结果为(标签名称已更改):

<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>

如果我在代码中使用该语句:

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 对象:

{"MyListResponse":
    {"customerSessionId":"xxcustomerSessionIdxx",
     "numberOfRecordsRequested":0,
     "moreResultsAvailable":false,
     "MyList":
        {"@size":"1",
         "@activePropertyCount":"1",
         "MySummary":
            {"@order":"0",
             "id":1234,
             "name":"...",
             .
             .
            }
        }
    }
 } 

result1 和 result2 的属性为 null 或默认值。类定义如下。我想将内容作为对象来读取,但我不能。您有什么建议来解决这个问题?我究竟做错了什么?提前致谢。

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 对象,但我应该编写更多的类来使其工作。

关于asp.net-mvc-4 - 使用 ReadAsAsync<T>() 反序列化复杂的 Json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23576726/

相关文章:

angular - Angular `HttpClient` `.get()` 泛型可以有非简单的属性类型吗? (例如 `string` 或 `number` 除外)

asp.net-mvc-4 - MVC 脚手架 - 实现分页的快速简便方法?

asp.net-mvc - ASP.NET MVC 4 异步子操作

c# - WPF中奇怪的缩放问题

.net-core - 如何在 .NET Core 3 中不使用 RestSharp 代理

android - 如何使用 REST 使用 Post 方法在 android 中获取 XML 信息?

asp.net-mvc-4 - ASP.net Web API - 将数组名称添加到输出

Javascript Ajax 回调函数未定义错误

c# - 使用 Web 请求为函数编写单元测试

c# - 使用 EntityFramework 源项目而不是其程序集的解决方案无法成功启动