Shabir jan
Shabir jan

Reputation: 2427

Generic Method Json Parsing

I have this generic method which is used for executing Post request and then parsing the response like this.

private async Task<object> PostAsync<T1,T2>(string uri, T2 content)
{
    using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, uri))
    {
        var json = JsonConvert.SerializeObject(content);
        using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json"))
        {
            requestMessage.Content = stringContent;

            HttpResponseMessage response = await _client.SendAsync(requestMessage);
            if (response.IsSuccessStatusCode)
            {
                _logger.LogInformation("Request Succeeded");

                T1 responseModel = JsonConvert.DeserializeObject<T1>(await response.Content.ReadAsStringAsync());
                return  responseModel;
            }
            else
            {
                return await GetFailureResponseModel(response);

            }
        }
    }
}

Now the issue is that some Post request response are in SnakeCase and others are in CamelCase. How can I fix this issue.

Upvotes: 1

Views: 68

Answers (1)

Camilo Terevinto
Camilo Terevinto

Reputation: 32088

Given that you know at compile-time when you know snake_case and when you need the default strategy, you could just do this:

private Task<object> PostAsync<T1, T2>(string uri, T2 content)
{
    return PostAsync<T1, T2>(uri, content, new DefaultNamingStrategy());
}

private async Task<object> PostAsync<T1, T2>(string uri, T2 content, NamingStragy namingStrategy)
{
    using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, uri))
    {
        var json = JsonConvert.SerializeObject(content);
        using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json"))
        {
            requestMessage.Content = stringContent;

            HttpResponseMessage response = await _client.SendAsync(requestMessage);
            if (response.IsSuccessStatusCode)
            {
                _logger.LogInformation("Request Succeeded");

                var deserializerSettings = new JsonSerializerSettings
                {
                    ContractResolver = new DefaultContractResolver
                    {
                        NamingStrategy = namingStrategy
                    }
                };

                T1 responseModel = JsonConvert.DeserializeObject<T1>(await response.Content.ReadAsStringAsync(), deserializerSettings);
                return responseModel;
            }
            else
            {
                return await GetFailureResponseModel(response);

            }
        }
    }
}

So, when you need the default strategy:

await PostAsync<Some1, Some2>(uri, some2Content);

and, when you need snake_case:

await PostAsync<Some1, Some2>(uri, some2Content, new SnakeCaseNamingStrategy());

Upvotes: 2

Related Questions