Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Response Serialization Issue

I am facing a weird issue maybe I am doing something wrong here. So I am working on WebApi Project using .Net Core 2.2. And In that I am calling Api from another server and I am parsing the response into this Model.

 public class LoginResponseModel
{
    [JsonProperty(PropertyName = "token_type")]
    public string tokenType { get; set; }

    [JsonProperty(PropertyName = "access_token")]
    public string accessToken { get; set; }

    [JsonProperty(PropertyName = "expires_in")]
    public string expiresIn { get; set; }

    [JsonProperty(PropertyName = "refresh_token")]
    public string refreshtToken { get; set; }
}

As from above model you can see from Api I am getting response in SnakeCase and I my model parameters are in CamelCase. When I Deserialize my Api Response:

 T1 responseModel = JsonConvert.DeserializeObject<T1>(await response.Content.ReadAsStringAsync());

Here T1 is LoginResponseModel And it successfully parse the Api Response in my model, see the attached screenshot, enter image description here

But when I call my Api which is calling another api whose response I just parsed (above example) the response returned is in SnakeCase. See ScreenShot enter image description here

Clarification Just to clarify Mobile App calls my Api i.e Login() and than my Login Methods calls another Api from another server i.e AuthenticateUser(...). So response of AuthenticateUser is SnakeCase which I am parsing into my LoginResponseModel and than that response is returned as Login api response. But than I am getting response with SnakeCase

Can someone please tell me what I am missing here or what can be done to fix that. I don't want to use another Model to transform to my desired response.

Update @Darkonekt Answer helped me, but now I am facing another issue in Serialization & Deserialization. So this is my Generic Method for PostAsync

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");
                    var dezerializerSettings = new JsonSerializerSettings
                    {
                        ContractResolver = new DefaultContractResolver
                        {
                            NamingStrategy = new SnakeCaseNamingStrategy()
                        }
                    };
                    T1 responseModel = JsonConvert.DeserializeObject<T1>(await response.Content.ReadAsStringAsync(), dezerializerSettings);
                    return  responseModel;
                }
                else
                {
                    return await GetFailureResponseModel(response);

                }
            }
        }
    }

As this Method is generic and will be used for any other Post Request, but as here I am setting Deserializer as SnakeCase and it works fine when api response is in SnakeCase, but issue occurs when my other Post Request returns response in CamelCase. I am getting Null values as parsing fails. How can I fix this issue as well.

like image 504
Shabir jan Avatar asked Jul 06 '26 15:07

Shabir jan


1 Answers

The [JsonProperty(PropertyName = "refresh_token")] Attribute is a two way street.

It is applied when serializing and when deserializing.

If you want to have a different name on serialization you will need ContractResolver and your own settings.

Look at this stackoverflow question on details how to do it: Serialize and Deserialize with different property names

Or you will need to create two models one for serialization and one for deserialization and map between them and then return the model that has no attributes.

like image 88
Jonathan Alfaro Avatar answered Jul 09 '26 03:07

Jonathan Alfaro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!