.net HttpClient with custom JsonConverter

前端 未结 3 896
离开以前
离开以前 2020-12-16 14:14

I\'m using .NET\'s HttpClient to make requests to a WebAPI that returns some JSON data that requires a little bit of custom deserialization on the client\'s side. For this

相关标签:
3条回答
  • 2020-12-16 14:48

    I was able to add a custom JsonConverter to the default formatters for HttpClient with the following:

    MediaTypeFormatterCollection formatters = new MediaTypeFormatterCollection(); 
    formatters.JsonFormatter.SerializerSettings.Converters.Add(new MyCustomConverter());
    
    
    var result = response.Content.ReadAsAsync<T>(formatters).Result;
    

    This seemed to allow you to just add your custom converter to the default converters.

    0 讨论(0)
  • 2020-12-16 14:52

    May be you would like to use HttpClient.GetStringAsync Method (String)

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

    Or what exactly you want to be more elegant?

    0 讨论(0)
  • 2020-12-16 14:54

    You can pass the JsonSerializerSettings with the list of your converters to the JsonMediaTypeFormatter which will be used by ReadAsAsync<T>:

    i.e.

    var obj = await result.Content.ReadAsAsync<refsResponse>(
        new[] {new JsonMediaTypeFormatter {
              SerializerSettings = new JsonSerializerSettings { 
                  Converters = new List<JsonConverter> {
                    //list of your converters
                   }
                 } 
              }
        });
    
    0 讨论(0)
提交回复
热议问题