简体   繁体   中英

Properties missing in JSON data deserialization with Model in .NET Core-6.0

my project is .NET 6.0.

I have an issue After deserializing the JSON data with PriceVM class Show, Ticket fields are missing in the postman output.

this is the JSON output without deserializing with model

{
    "traceId": "fhregtkgregtireuiti3t",
     "data": {
        "airPrice":[
            {
                "key":"kjewqerlewqwwq",
                "show":true,
                "showSpecified":true,
                "departure":"2022-06-28T19:08:00.000+01:00",
                "solution":[
                    {
                        "ticket":false,
                        "ticketSpecified":false,
                        "origin":"JED",
                        "exchange":false
                    },
                    {
                        "ticket":false,
                        "ticketSpecified":false,
                        "origin":"MND",
                        "exchange":false
                    },
                ]   
            }
        
        ]
     
     }
}

I created below class with above JSON result

public class PriceVM{

 [JsonProperty("traceId")]
 public string TraceId {get;set;}

 [JsonProperty("data")]
 public Data Data {get;set;}
 
}

public class Data {

 [JsonProperty("airPrice")]
 public IEnumerable<AirPrice> AirPrice {get;set;}

}

public class AirPrice{
 
 [JsonProperty("airPrice")]
 public string Key {get;set;}

 [JsonProperty("show")]
 public bool Show {get;set;}

 [JsonProperty("showSpecified")]
 public bool ShowSpecified {get;set;}

 [JsonProperty("departure")]
 public DateTime Departure {get;set;}

 [JsonProperty("solution")]
 public List<Solution> Solution {get;set;}

} 

public class Solution{

 [JsonProperty("ticket")]    
 public bool Ticket {get;set;}

 [JsonProperty("ticketSpecified")]    
 public bool TicketSpecified {get;set;}

 [JsonProperty("origin")]
 public string Origin {get;set;}

 [JsonProperty("exchange")]
 public bool Exchange {get;set;}

}

I get the above-structured JSON data from API in this function

public async Task<PriceVM> Handle(PriceQuery request)
{
    
 var response= await client.PostAsJsonAsync<ADT>("url",request);
 response.EnsureSuccessStatusCode();
 string responseBody = await response.Content.ReadAsStringAsync();
 
  var airPrice = (JsonConvert.DeserializeObject<PriceVM>(responseBody, new JsonSerializerSettings
        {
            DateParseHandling = DateParseHandling.None,    
 }));

}

if I deserialize with the above method output is as below Show, Ticket properties are missing

 {
        "traceId": "fhregtkgregtireuiti3t",
         "data": {
            "airPrice":[
                {
                    "key":"kjewqerlewqwwq",
                    "showSpecified":true,
                    "departure":"2022-06-28T19:08:00.000+01:00",
                    "solution":[
                        {
                            "ticketSpecified":false,
                            "origin":"JED",
                            "exchange":false
                        },
                        {
                            "ticketSpecified":false,
                            "origin":"MND",
                            "exchange":false
                        },
                    ]   
                }
            
            ]
         
         }
    }

// endpoint

[HttpPost]
[Route("price")]
public async Task<ActionResult<PriceVM>> AirPrice( [FromBody] ADT dto)
{

    var result = await pricesrvice.Handle(dto);
    
    return Ok(result);
}

but when I debug the API request; in the controller endpoint I can view the result has Show, Ticket properties and their values as well.

if I deserialized the JSON result like below all fields are in postmen output

var airPrice = (JsonConvert.DeserializeObject(responseBody, new JsonSerializerSettings
    {
           DateParseHandling = DateParseHandling.None,    
    }));

output

  {
        "traceId": "fhregtkgregtireuiti3t",
         "data": {
            "airPrice":[
                {
                    "key":"kjewqerlewqwwq",
                    "show":true,
                    "showSpecified":true,
                    "departure":"2022-06-28T19:08:00.000+01:00",
                    "solution":[
                        {
                            "ticket":false,
                            "ticketSpecified":false,
                            "origin":"JED",
                            "exchange":false
                        },
                        {
                            "ticket":false,
                            "ticketSpecified":false,
                            "origin":"MND",
                            "exchange":false
                        },
                    ]   
                }
            
            ]
         
         }
    }

The error is if name and value of 2 near property is same it return one property. example

ticket,ticketSpecified

to sortout this i add below configuration in

Program.cs

file

builder.Services.AddControllers(options =>
                options.Filters.Add<ApiExceptionFilterAttribute>())
                    .AddFluentValidation()

.AddNewtonsoftJson(options =>
{
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

**// Added code**
    options.SerializerSettings.ContractResolver = new DefaultContractResolver()
  {
        IgnoreIsSpecifiedMembers = false,
    };
});

then it returns All properties

but when I log in via UI can not log in

but no error shown in the console in the development and production environment

if I comment these code can login and work as usual

options.SerializerSettings.ContractResolver = new DefaultContractResolver()
  {
        IgnoreIsSpecifiedMembers = false,
    };

please help me to sort out this error

The last issue is it returns data in pascal Case because of DefaultContractResolver . but by default, it returns data in camel Case

to overcome that issue I configure Program. cs Program. cs

builder.Services.AddControllers(options =>
                options.Filters.Add<ApiExceptionFilterAttribute>())
                    .AddFluentValidation()

.AddNewtonsoftJson(options =>
{
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

**// Replace below code **
    options.SerializerSettings.ContractResolver = new DefaultContractResolver()
  {
        IgnoreIsSpecifiedMembers = false,
    };

 // with

 options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver()
        {
            IgnoreIsSpecifiedMembers = true,
        };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM