Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I map a GraphQL response with a JSON array property in C#?

Mapping C# Class to GraphQL Response.

Hi,

I am learning GraphQL and how to query/commuicate with a GraphQL endpoint. The json response looks like the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "data": {
    "allFilms": {
      "films": [
        {
          "title": "A New Hope",
          "releaseDate": "1977-05-25"
        },
        {
          "title": "The Empire Strikes Back",
          "releaseDate": "1980-05-17"
        },
        {
          "title": "Return of the Jedi",
          "releaseDate": "1983-05-25"
        },
        {
          "title": "The Phantom Menace",
          "releaseDate": "1999-05-19"
        },
        {
          "title": "Attack of the Clones",
          "releaseDate": "2002-05-16"
        },
        {
          "title": "Revenge of the Sith",
          "releaseDate": "2005-05-19"
        }
      ]
    }
  }
}

I am having a difficult time trying to map my response object accordingly. This is what I have so far:

   public class GraphQLFilmResponse
{
    public allFilms allFilms { get; set; }
}

public class allFilms
{
    public films films { get; set; }
}

public class films
{
    public List<film> film { get; set; }
}

public class film
{
    public string title { get; set; }
    public DateTime? releaseDate { get; set; }
}

The error message is as follows:
Message=Cannot deserialize the current JSON array (e.g. [1,2,3]) into type ‘GraphQL.films’ because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

Any help or links (I am sure someone asked this question already) would be appreciated.

>Solution :

public class Data
{
    public AllFilms AllFilms { get; set; }
}

public class AllFilms
{
    public List<Film> Films { get; set; }
}

public class Film
{
    public string Title { get; set; } = string.Empty;
    public DateTime? ReleaseDate { get; set; }
}

Deserialize object:

option = new JsonSerialiazerOption(){ PropertyNameCaseInsensitivity = true};
var data = JsonSerializer.Deserialze<Data>(response, options);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading