反序列化Web Api OData响应

Raf*_*aeu 1 c# linq serialization json odata

我有一个由OData V4控制器返回的Entity Framework对象。我返回一个IQueryable,并且如果我在不带任何OData子句的情况下调用OData端点,则可以成功执行此操作:

var content = response.Content.ReadAsAsync<IQueryable<Person>>();
Run Code Online (Sandbox Code Playgroud)

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"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

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

无法反序列化当前JSON对象(例如{“ name”:“ value”})为类型'System.Linq.IQueryable`1 [xxx.Person]',因为该类型需要JSON数组(例如[1,2,3] )正确反序列化。

响应如下:

{
  "@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"
      }
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

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

小智 5

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

var content = response.Content.ReadAsAsync<ODataResponse<Person>>();
Run Code Online (Sandbox Code Playgroud)

其中ODataResponse是:

internal class ODataResponse<T>
{
    public T[] Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)