0

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:

{
  "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.

1
  • You don't have a class that represents "data". Commented May 23, 2023 at 19:14

1 Answer 1

1
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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Bane. I guess youtube videos only get me so far. =) Thank you again. Works great!!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.