我正在使用.NET的HttpClient向WebAPI发出请求,该WebAPI返回一些JSON数据,该数据需要在客户端进行一些自定义反序列化。为此,我已经完成了自己的工作JsonConverter,但是我不知道如何让该ReadAsAsync<T>方法处理转换器的存在。
JsonConverter
ReadAsAsync<T>
通过使用ReadAsStringAsync读取响应,然后将该字符串传递给JsonConvert.DeserializeObject,我已经解决了我的问题,但是似乎应该有一个更优雅的解决方案。
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; }
您可以将JsonSerializerSettings转换器列表与一起传递给,供JsonMediaTypeFormatter以下人员使用ReadAsAsync<T>:
JsonSerializerSettings
JsonMediaTypeFormatter
即
var obj = await result.Content.ReadAsAsync<refsResponse>( new[] {new JsonMediaTypeFormatter { SerializerSettings = new JsonSerializerSettings { Converters = new List<JsonConverter> { //list of your converters } } } });