.NET HttpClient的自定义JsonConverter(.net HttpClient w

2019-07-05 13:43发布

我使用.NET的HttpClient的发出请求到返回需要自定义反序列化的客户端的一边一点点一些JSON数据的WebAPI。 为此,我做了我自己的JsonConverter ,但我无法弄清楚如何有ReadAsAsync<T>方法拿起转换器的存在。

我已经解决了我的问题,现在通过使用ReadAsStringAsync读取响应,然后通过该字符串中JsonConvert.DeserializeObject ,但似乎应该有一个更好的解决方案。

这里是我的代码:

public PrefsResponse GetAllPrefs(string sid) {
    HttpClient client = CreateHttpClient(null, sid);
    var response = client.GetAsync("api/sites/" + sid).Result;

    // TODO : find a way to hook custom converters to this...
    // return response.Content.ReadAsAsync<PrefsResponse>().Result;

    var stringResult = response.Content.ReadAsStringAsync().Result;

    return JsonConvert.DeserializeObject<PrefsResponse>(stringResult, new PrefClassJsonConverter());
}

这是我能做到的最好,或者是有一些更优雅的方式?

这里就是我创建HttpClient的同时,如果这就是我需要把它挂:

        private HttpClient CreateHttpClient(CommandContext ctx, string sid) {
        var cookies = new CookieContainer();

        var handler = new HttpClientHandler {
            CookieContainer = cookies,
            UseCookies = true,
            UseDefaultCredentials = false
        };

        // Add identity cookies:
        if (ctx != null && !ctx.UserExecuting.IsAnonymous) {
            string userName = String.Format("{0} ({1})", ctx.RequestingUser.UserName, ctx.UserExecuting.Key);
            cookies.Add(new Cookie(__userIdCookieName, userName));
            cookies.Add(new Cookie(__sidCookieName, sid));
            cookies.Add(new Cookie(__hashCookieName,
                                   GenerateHash(userName, Prefs.Instance.UrlPrefs.SharedSecret)));
        }

        var client = new HttpClient(handler) {
            BaseAddress = _prefServerBaseUrl
        };

        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));



        return client;
    }

Answer 1:

您可以通过JsonSerializerSettings与转换器的列表JsonMediaTypeFormatter将由使用ReadAsAsync<T>

var obj = await result.Content.ReadAsAsync<refsResponse>(
    new[] {new JsonMediaTypeFormatter {
          SerializerSettings = new JsonSerializerSettings { 
              Converters = new List<JsonConverter> {
                //list of your converters
               }
             } 
          }
    });


Answer 2:

可能是你想使用HttpClient.GetStringAsync方法(String)

var response = client.GetStringAsync("api/sites/" + sid);
return JsonConvert.DeserializeObject<PrefsResponse>(response.Result, new  PrefClassJsonConverter());

或者你想要什么更优雅?



Answer 3:

我能够自定义JsonConverter添加到默认格式化了的HttpClient有以下几点:

MediaTypeFormatterCollection formatters = new MediaTypeFormatterCollection(); 
formatters.JsonFormatter.SerializerSettings.Converters.Add(new MyCustomConverter());


var result = response.Content.ReadAsAsync<T>(formatters).Result;

这似乎让你自定义转换器只需添加到默认的转换器。



文章来源: .net HttpClient with custom JsonConverter