.net HttpClient与自定义JsonConverter

时间:2012-12-17 13:54:14

标签: .net json asp.net-web-api dotnet-httpclient

我正在使用.NET的HttpClient向WebAPI发出请求,该请求返回一些需要在客户端进行一些自定义反序列化的JSON数据。为此,我已经创建了自己的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;
    }

3 个答案:

答案 0 :(得分:15)

您可以将包含转换器列表的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
               }
             } 
          }
    });

答案 1 :(得分:1)

您可能希望使用HttpClient.GetStringAsync Method (String)

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

或者你想要更优雅的是什么?

答案 2 :(得分:1)

我能够使用以下内容将自定义JsonConverter添加到HttpClient的默认格式化程序中:

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


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

这似乎允许您只将自定义转换器添加到默认转换器。