简体   繁体   English

如何将具有OData的HttpResponseMessage转换为C#对象?

[英]How to convert HttpResponseMessage having OData to a C# object?

I am calling a REST service from my C# application which connects to CRM. 我从连接到CRM的C#应用​​程序调用REST服务。 This returns HttpResponseMessage. 这将返回HttpResponseMessage。

response.Content.ReadAsStringAsync().Result

The above statement returns following output. 以上语句返回以下输出。 I need to convert this to Account object, which already has "accountnumber, and accountid properties. 我需要将其转换为Account对象,它已经具有“accountnumber和accountid属性。

{ {
"@odata.context":" https://APIURL/api/data/v8.1/ $metadata#account(accountnumber)","value":[ { "@odata.etag":"W/\\"12496866\\"","accountnumber":"D00208","accountid":"30417c0f-7b8c-e611-80f3-5065f38bd4d1" } ] } “@ odata.context”:“ https://APIURL/api/data/v8.1/ $ metadata#account(accountnumber)”,“value”:[{“@ odata.etag”:“W / \\”12496866 \\“”,“accountnumber”:“D00208”,“accountid”:“30417c0f-7b8c-e611-80f3-5065f38bd4d1”}]}

I have tried following code 我试过以下代码

Account return = JsonConvert.DeserializeObject<Account>(response.Content.ReadAsStringAsync().Result);

But this doesn't fill up the object, and it always has null values in accountnumber, and accountid fields. 但是这不会填满对象,并且它在accountnumber和accountid字段中始终具有空值。

Any idea of how to properly convert this response to the C# type. 知道如何正确地将此响应转换为C#类型。

you should do it like this - 你应该这样做 -

public class Value
{
    [JsonProperty("@odata.etag")]
    public string etag { get; set; }
    public string accountnumber { get; set; }
    public string accountid { get; set; }
}

public class RootObject
{
    [JsonProperty("@odata.context")]
    public string context { get; set; }
    public List<Value> value { get; set; }
}

then deserialize- 然后反序列化 -

var value = JsonConvert.DeserializeObject<RootObject>(json);

We can parse and create Anonymous Type based on that. 我们可以基于此解析并创建Anonymous Type In your case, replace the Anonymous Type with Account object. 在您的情况下,将Anonymous Type替换为Account对象。

Given the JSON string: 给定JSON字符串:

string json = @"{
   '@odata.context':'https://APIURL/api/data/v8.1/$metadata#account(accountnumber)',
   'value':[
      {
         '@odata.etag':'W/\'12496866\'',
         'accountnumber':'D00208',
         'accountid':'30417c0f-7b8c-e611-80f3-5065f38bd4d1'
      }
   ]
}";

It can be parsed as below: 它可以解析如下:

var jsonObject = JObject.Parse(json);
var dataObject = new
{
    Context = jsonObject["@odata.context"],
    Values = jsonObject["value"].AsEnumerable<JToken>()
                                .Select(v => new
                                {
                                    ETag = v["@odata.etag"],
                                    AccountNumber = v["accountnumber"],
                                    AccountId = v["accountid"]
                                }).ToArray()
};

In order to convert to Account object where the object is defined as below: 为了转换为Account对象,其中对象定义如下:

public class Account
{
    public string Number { get; set; }
    public string Id { get; set; }
}

Then the JSON object can be parsed as below (if looking for only first node; It can also be converted to list of Account s: 然后可以如下解析JSON对象(如果只查找第一个节点;它也可以转换为Account的列表:

var jsonObject = JObject.Parse(json);
var account = jsonObject["value"].AsEnumerable<JToken>()
                                 .Select(v => new Account()
                                 {
                                     Number = v["accountnumber"].ToString(),
                                     Id = v["accountid"].ToString()
                                 }).FirstOrDefault();

You can generalize the accepted answer by using a generic class to deserialize json web response: 您可以使用泛型类对json Web响应进行反序列化来概括接受的答案:

     class RootObject<T>
     {
        public List<T> Value { get; set; }
     }

     var odata  = JsonConvert.DeserializeObject<RootObject<POCO>>(json);

Try it with live Demo 试试现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM