System.Text.Json Deserialize doesn’t work for a GraphQL response

System.Text.Json Deserialize doesn’t work for a GraphQL response


0

I am working on a .NET 6 application using GraphQL and System.Text.Json. For the a shared util function:

public async Task<GraphQlResponse<T>> Query<T>(string mutation, IQueryInput variables = null)
{
    var content = JsonSerializer.Serialize(new { query = mutation, variables = (object) variables });
    var request = new HttpRequestMessage
                {
                    Method = HttpMethod.Post,
                    RequestUri = new Uri(baseUrl),
                    Content = new StringContent(content, Encoding.UTF8, "application/json")
                };
                
    logger.LogInformation("sending query:" + baseUrl + " with payload:" + content);

    var response = await queryPolicy.ExecuteAsync(context => httpClient.SendAsync(request, _cancellationToken), new Context().WithLogger(logger));;

    string responseBody = await response.Content.ReadAsStringAsync();

    logger.LogInformation("received response for - "+ baseUrl + " :" + response.StatusCode + " - " + responseBody); // I can see the responseBody

    response.EnsureSuccessStatusCode();
                
    var options = new JsonSerializerOptions();
    options.Converters.Add(new JsonStringEnumConverter());
    
    var res = JsonSerializer.Deserialize<GraphQlResponse<T>>(responseBody, options);
    return res; // it is always null
}

For my specific case, the JsonSerializer.Deserialize<GraphQlResponse<T>>(responseBody, options) doesn’t work. However, I am able to see the responseBody shows like this by log:

{
  "data": {
    "agreements": [
      {
        "agreementID": 100
      }
    ]
  }
}

GraphqQLResponse is like this:

public class GraphQlResponse<T>
{
        [JsonPropertyName("errors")]
        public IList<GraphQlError> Errors { get; set; }

        [JsonPropertyName("data")]
        public GraphQlData<T> Data { get; set; }

        public GraphQlResponse()
        {
            Errors = new List<GraphQlError>();
        }
}

GraphQLData looks like this:

public class GraphQlData<T>
{
    [JsonPropertyName("results")]
    public T Results { get; set; }
}

This query function is been called like this:

var response = await _graphqlClient.Query<List<AgreementResponse>>(query, variables);
return response.Data.Results; // is always null

AgreementResponse:

public class AgreementResponse
{
    [JsonPropertyName("Agreements")]
    public List<AgreementOutput> Agreements { get; set; }
}

AgreementOuput:

public class AgreementOutput
{
    [JsonPropertyName("agreementID")]
    public int AgreementID { get; set; }
}

This Query<T> function has been used in many places which is working fine, but no idea why it’s not able to deserialize this specific case and there NO Error or throw any exceptions. Any thoughts? Thanks a lot in advance!

3

  • 2

    Where's the JSON property results that the GraphQlData<T>.Results C# property maps with?

    – gunr2171

    1 hour ago


  • Without a custom converter, every property in the JSON has to map to a corresponding property in the C# type. To match the posted JSON, GraphQlData's Data would have to be a T directly, and you'd have to call it by passing AgreementResponse, not List<AgreementResponse> to Query.

    – Etienne de Martel

    1 hour ago


  • Haven't tried them, but I found these nugets, which might help: nuget.org/packages/GraphQL.Client.Serializer.SystemTextJson and nuget.org/packages/GraphQL.SystemTextJson,

    – dbc

    17 mins ago



Load 6 more related questions


Show fewer related questions

0



Leave a Reply

Your email address will not be published. Required fields are marked *