Rob G
Rob G

Reputation: 143

Deserialize GraphQLResponse / JSON array in c#

I am trying to deserialize a GraphQLResponse in c#.

My response contains the following:

{
  "myClassObjects": [
    {
      "var1": "var1Value",
      "var2": "var2Value"
    }, //more MyClass objects
]}

According to several sources, I should now be able to unpack and deserialize this using:

var output = response.getDataFieldAs<IEnumerable<MyClass>>("myClassObjects");

Sadly, the getDataFieldAs method does not exist (anymore).

The response.Data is a Newtonsoft.Json.Linq.JObject which contains an object "myClassObjects" which is an array of MyClass objects. When I try to unpack :

List<MyClass> output = JsonConvert.DeserializeObject<List<MyClass>>(response.Data.ToString());

I keep getting :

Cannot deserialize the current JSON object ... because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly

It's my first time working with Json and I really hope there is a handy sollution for this ? Any help would be much appreciated.

Upvotes: 1

Views: 1608

Answers (1)

Jawad
Jawad

Reputation: 11364

you're missing the rootObject when deserializing the "array" of, what i am assuming, is your MyClass objects.

public class RootObject {
  [JsonProperty("myClassObjects")]
  public List<MyClass> MyClassObjects {get;set; }
}

// then deserialize your json like this,
var obj = JsonConvert.DeserializeObject<RootObject>(response.Content); 

Without the details on how you are getting the response, i am not sure how to explain the difference in response.Content vs response.Data. If you are using RestSharp, then Data would have the correctly deserialized data for you. Content is the raw string that you would deserialize yourself.

The error you keep getting is because you are deserializing the Json as [ ] but its { property: value }. Your json has an object that has an array instead of json being an array of objects.

Upvotes: 2

Related Questions