Search code examples
c#jsonapiasp.net-web-apidynamics-crm

How to convert HttpResponseMessage having OData to a C# object?


I am calling a REST service from my C# application which connects to CRM. This returns 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.

{
"@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.

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


Solution

  • 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);