Home > database >  Problem Deserializing JSON to objects in C#
Problem Deserializing JSON to objects in C#

Time:01-31

I have the below response from the API in a console application written in C#:

{
  "d": {
    "results": [
      {
        "__metadata": {
          "id": "123",
          "uri": "456",
          "type": "789"
        },
        "PERNR": "1",
        "USRID": "2"
      },
      {
        "__metadata": {
          "id": "159",
          "uri": "951",
          "type": "753"
        },
        "PERNR": "4",
        "USRID": "6"
      }
    ]
  }
}

And used the below code to deserialize:

    public class d
    {
        public results results { get; set; }
    }

    public class results
    {
        public string PERNR { get; set; }
        public string USRID { get; set; }
        public __metadata __metadata { get; set; }
    }

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

        var serilizer = new JavaScriptSerializer();
        d output = serilizer.Deserialize<d>(response.Content);

But the result is null. Is there any problem in the definition of the classes?

CodePudding user response:

The properties should start with a capital letter, to match the case of the properties in the JSON response. Change the class definitions as follows:

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

public class Results
{
public string PERNR { get; set; }
public string USRID { get; set; }
public Metadata __metadata { get; set; }
}

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

Change deserialize line to:

var serilizer = new JavaScriptSerializer();
D output = serilizer.Deserialize<D>(response.Content);

CodePudding user response:

The issue is results is an array in your json, where in your class, it is an object. Change it to

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

CodePudding user response:

If you use a JSON to C# converter like json2csharp or Visual Studio's Paste JSON As Classes you'll get :

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

public class D
{
    public List<Result> results { get; set; }
}

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

public class Result
{
    public Metadata __metadata { get; set; }
    public string PERNR { get; set; }
    public string USRID { get; set; }
}

There are two important differences :

  1. The JSON document contains a root element with an attribute named d, not a D object
  2. D.results is a collection of Result objects, not a single object
  • Related