Home > Blockchain >  How to deserialize oData V2 with JSON in C#?
How to deserialize oData V2 with JSON in C#?

Time:10-31

I am trying to deserialize oData V2 with C#, but Value is allways null:

    {
    "d": {
        "results": [
        {
            "__metadata": {
            "id": "http://vhcalnplci:8000/sap/opu/odata/SAP/ZEMPLOYEE_SRV/EmployeeEntitySet('111111')",
            "uri": "http://vhcalnplci:8000/sap/opu/odata/SAP/ZEMPLOYEE_SRV/EmployeeEntitySet('111111')",
            "type": "ZEMPLOYEE_SRV.EmployeeEntity"
            },
            "Empno": "111111",
            "Fname": "Test Firstname",
            "Lname": "Test Lastname",
            "Addrs": "Test Address",
            "Desgn": "Test Job"
            }
        ]
    }
}

I've tried CLR Class Generation in Visual Studio, and created the following classes

public class Rootobject
    {
        public D d { get; set; }
    }

    public class D
    {
        public Result[] results { get; set; }
    }

    public class Result
    {
        public __Metadata __metadata { get; set; }
        public string Empno { get; set; }
        public string Fname { get; set; }
        public string Lname { get; set; }
        public string Addrs { get; set; }
        public string Desgn { get; set; }
    }

    public class __Metadata
    {
        public string id { get; set; }
        public string uri { get; set; }
        public string type { get; set; }
    }

    internal class OData<Result>
    {
        public List<Result> Value { get; set; }
    }

Method I've used where Result is always zero

using (var client = new HttpClient())
 {
     HttpResponseMessage response = await client.GetAsync(new Uri(url));
     var json = await response.Content.ReadAsStringAsync();
     var result = JsonConvert.DeserializeObject<OData<Employee>>(json);
     var employee = result.Value;
 }

Can you please tell me what I'm doing wrong. Thanks!

CodePudding user response:

Change this line

 var result = JsonConvert.DeserializeObject<OData<Employee>>(json);

into

 var result = JsonConvert.DeserializeObject<Rootobject>(json); 
  • Related