首页 文章

反序列化Web Api OData响应

提问于
浏览
1

我有一个由OData V4控制器返回的Entity Framework对象 . 我返回一个IQueryable,如果我调用没有任何OData子句的OData endpoints ,我可以成功地执行此操作:

var content = response.Content.ReadAsAsync<IQueryable<Person>>();

JSON中的响应如下:

{
  "@odata.context":"http://xxx:8082/odata/$metadata#Persons","value":[
    {
      "Id":"291b9f1c-2587-4a35-993e-00033a81f6d5",
      "Active":true,
      "Alert":"Some alerts for the Person",
      "Comments":"Some comments for the Person"
    }
  ]
}

但是一旦我开始使用OData,例如在Complex属性上使用$ expand,我就会得到以下异常:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Linq.IQueryable`1[xxx.Person]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

响应如下:

{
  "@odata.context":"http://aqavnext01:8082/odata/$metadata#Persons","value":[
    {
      "Id":"291b9f1c-2587-4a35-993e-00033a81f6d5",
      "Active":true,
      "Alert":"Some alerts for the Person",
      "Comments":"Some comments for the Person",
      "Party":{
        "Id":"291b9f1c-2587-4a35-993e-00033a81f6d5"
      }
    }
  ]
}

我正在反序列化使用我的Web Api返回的相同对象,所以我不明白为什么它失败了 . 应用$ select时出现同样的问题 .

1 回答

  • 4

    尝试反序列化这样的内容:

    var content = response.Content.ReadAsAsync<ODataResponse<Person>>();
    

    ODataResponse的位置是:

    internal class ODataResponse<T>
    {
        public T[] Value { get; set; }
    }
    

相关问题