本文介绍了如何将具有 OData 的 HttpResponseMessage 转换为 C# 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从连接到 CRM 的 C# 应用程序调用 REST 服务.这将返回 HttpResponseMessage.

I am calling a REST service from my C# application which connects to CRM.This returns HttpResponseMessage.

response.Content.ReadAsStringAsync().Result

上述语句返回以下输出.我需要将其转换为 Account 对象,该对象已经具有accountnumber 和 accountid 属性.

The above statement returns following output. I need to convert this to Account object, which already has "accountnumber, and accountid properties.

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

我尝试了以下代码

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

但这并不会填充对象,并且它在 accountnumber 和 accountid 字段中始终具有空值.

But this doesn't fill up the object, and it always has null values in accountnumber, and accountid fields.

有关如何将此响应正确转换为 C# 类型的任何想法.

Any idea of how to properly convert this response to the C# type.

推荐答案

你应该这样做 -

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

然后反序列化-

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

这篇关于如何将具有 OData 的 HttpResponseMessage 转换为 C# 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 09:37