Home > Enterprise >  Is there a way to deserialize json object when using dynamic in C#?
Is there a way to deserialize json object when using dynamic in C#?

Time:01-04

I have a graphql executioner code that looks like this:

public async Task<T> ExecuteGQlQuery<T>(string url, string reqQuery, AuthenticationHeaderValue credentials, object variables)
{
    try
    {
        var graphQLClient = new GraphQLHttpClient(url, new SystemTextJsonSerializer());
        graphQLClient.HttpClient.DefaultRequestHeaders.Authorization = credentials;

        var gQLRequest = new GraphQLRequest
        {
            Query = reqQuery,
            Variables = variables
        };

        var response = await graphQLClient.SendQueryAsync<T>(gQLRequest);

        return response.Data;
    }
    catch (Exception)
    {
        throw;
    }
}

This works fine when I send in a specific type that I want the data to be converted to.

I have a scenario where I want to fetch data and what ever I get back I just want to forward it to the frontend without converting it to an object type so I used dynamic:

var data = await _executeService.ExecuteGQlQuery<dynamic>(myUrl, query, credentials, null);

I can see the json data but when I see the return I see

{"ValueKind":"Object"}

Is there a way to deserialize this correctly and what am I missing?

CodePudding user response:

So this took me a while and a few attempts.

I never considered that my GraphQLHttpClient settings were off since I was using SystemTextJsonSerializer

I added the GraphQL.Client.Serializer.Newtonsoft nuget package and changed from SystemTextJsonSerializer to NewtonsoftJsonSerializer

And it works now.

Also note that if you have a service in say a class library you will need to add GraphQL.Client.Serializer.Newtonsoft nuget package into your source project to get this working.

  • Related