Home > OS >  Mapping issue when Deserialising
Mapping issue when Deserialising

Time:11-01

I have the following code:

    using System.Text.Json;
    private async Task<AuditReviewerDelegationDto> GetDelegationAsync()
    {
        // TODO: Get current logged in user, pass mdmuseridentifier
        var mdmUserIdentifier = 248113;
        var response = LocalHttpClient.GetAsync(BaseAddress   "api/AuditReviewerDelegation/GetDelegation/"   mdmUserIdentifier).Result;

        response.EnsureSuccessStatusCode();

        var responseContent = await response.Content.ReadAsStringAsync();

        var tt = JsonSerializer.Deserialize<AuditReviewerDelegationDto>(responseContent);
        return tt;
    }

My variable responseContent has all the data that I expect. However, when I use the Deserialize method, my tt variable is empty. I believe the reason for this is that all the properties on the responseContent start with a lower case, but on my AuditReviewerDelegationDto they all start upper case. I cant change my model to be lowercase. Is there anyway I can either get the deserializer to ignore case or set the response object to retun camel case.

CodePudding user response:

Yes, in order to ignore the casing of your property names, you just need to set JsonSerializerOptions.PropertyNameCaseInsensitive to true. See this page for more details, but here's what that might look like in code:

var options = new JsonSerializerOptions
{
    PropertyNameCaseInsensitive = true
};
var tt = JsonSerializer.Deserialize<AuditReviewerDelegationDto>(responseContent, options);

However, if tt itself is null (rather than the individual properties of tt being null) you might have another problem - it depends on the actual text within responseContent.

  • Related