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.
>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);