0

I have response from OData api which looks like this below. I just want the api to return a list of objects with only three fields (i.e.) [datetime], [body],[subject].

 {
"d": {
    "results": [
        {
            "__metadata": {
                "id": "http://localhost:7305",
                "uri": "http://localhost:7305",
                "type": "Subject.Classifications"
            },
            "dateTime": "2020-06-25T11:31:51",
            "source": "JHGTY",
            "body": "The offering has now increased ",
            "subject": "Offering- updated",
            "Error": {
                "__deferred": {
                    "uri": "http://localhost:7305/"
                }
            }
        },
        {
            "__metadata": {
                "id": "http://localhost:7305",
                "uri": "http://localhost:7305",
                "type": "Subject.Classifications"
            },
            "dateTime": "2020-06-26T11:25:51",
            "source": "XFGFT",
            "body": "The offering has now degraded ",
            "subject": "Offering- updated",
            "Error": {
                "__deferred": {
                    "uri": "http://localhost:7305/"
                }
            }
        }
    ]
    }
    }

I have created a model like below:

 public class Classification
    {
        public DateTime dateTime { get; set; }
        public string body { get; set; }
        public string subject { get; set; }


    }

And I am trying to deserialize the response so it can return me a list but it throws an exception that it cannot be deserialized when I use the code below :

IRestResponse response = client.Execute(request);
List<Classification> classifications = JsonConvert.DeserializeObject<List<Classification>>(response.Content);

The exception I am getting is:

   Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[genie.Api.Controllers.ClassificationController+Classifications]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'd', line 1, position 5.

snowflakes74
  • 1,307
  • 1
  • 20
  • 43

1 Answers1

1

Your class does not fully represent your json structure (and your json in question misses some "'s in id properties in metadata). After fixing json you can try this:

public class Root
{
    [JsonProperty("d")]
    public D D { get; set; }
}

public class D
{
    [JsonProperty("results")]
    public List<Classification> Results { get; set; }
}

JsonConvert.DeserializeObject<Root>(response.Content)
Guru Stron
  • 102,774
  • 10
  • 95
  • 132