简体   繁体   English

在C#中使用dynamic时,有没有办法反序列化json object?

[英]Is there a way to deserialize json object when using dynamic in C#?

I have a graphql executioner code that looks like this:我有一个 graphql 刽子手代码,如下所示:

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 :我有一个场景,我想获取数据,无论我得到什么,我只想将它转发到前端而不将其转换为 object 类型,所以我使用了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我可以看到 json 数据,但是当我看到返回时,我看到了

{"ValueKind":"Object"}

Is there a way to deserialize this correctly and what am I missing?有没有办法正确反序列化,我错过了什么?

So this took me a while and a few attempts.所以这花了我一段时间和几次尝试。

I never considered that my GraphQLHttpClient settings were off since I was using SystemTextJsonSerializer自从我使用SystemTextJsonSerializer以来,我从未考虑过我的GraphQLHttpClient设置已关闭

I added the GraphQL.Client.Serializer.Newtonsoft nuget package and changed from SystemTextJsonSerializer to NewtonsoftJsonSerializer我添加了GraphQL.Client.Serializer.Newtonsoft nuget package 并从SystemTextJsonSerializer更改为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.另请注意,如果您有 class 库中的服务,则需要将GraphQL.Client.Serializer.Newtonsoft nuget package 添加到源项目中才能使其正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM