I have been using Xamarin Forms for a while but looking to start using .NET MAUI and I am having an issue when deserializing a response from my test API to a ViewModel List it is returning the list count but not binding the variables in the ViewModel if that makes sense.
I was using Newtonsoft which worked perfected but now I am on 6.0 I don’t believe they support it so I am using the System.Text.Json library instead.
The code that worked was:
var response = client.GetAsync("WeatherForecast?format=json").Result
if(response.IsSuccessStatusCode)
{
var result = JsonConvert.DeserializeObject<List<WeatherViewModel>>(response.Content.ReadAsStringAsync().Result);
}
But now when I use:
var response = client.GetAsync("WeatherForecast?format=json").Result;
if (response.IsSuccessStatusCode)
{
var options = new JsonSerializerOptions { WriteIndented = true };
var responseData = JsonSerializer.Deserialize<List<WeatherViewModel>>(response.Content.ReadAsStringAsync().Result, options);
}
It gives me this in the debugger
But in the actual response.Content.ReadAsStringAsync the result is the following:
The ViewModel is structured like this:
public class WeatherViewModel
{
public DateTime Date { get; set; }
public Int32 TemperatureC { get; set; }
public Int32 TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public String Summary { get; set; }
}
Here is the JSON it brings back from the call:
[
{
"date": "2023-02-15T18:42:26.4694349+00:00",
"temperatureC": 39,
"temperatureF": 102,
"summary": "Hot"
},
{
"date": "2023-02-16T18:42:26.4694515+00:00",
"temperatureC": -3,
"temperatureF": 27,
"summary": "Cool"
},
{
"date": "2023-02-17T18:42:26.4694523+00:00",
"temperatureC": -9,
"temperatureF": 16,
"summary": "Bracing"
},
{
"date": "2023-02-18T18:42:26.469453+00:00",
"temperatureC": 9,
"temperatureF": 48,
"summary": "Cool"
},
{
"date": "2023-02-19T18:42:26.4694537+00:00",
"temperatureC": 5,
"temperatureF": 40,
"summary": "Chilly"
}
]
So the problem I am having is that I am getting the JSON ok from the API Get but when I deserialize it it is not populating into the ViewModel but it is creating 5 counts in the list. Could anybody shed some light on this for me. It would be a massive help.
>Solution :
it is always bad idea to post images instead of text, so I can’t even see what is the problem, but I can see that you must be need to add PropertyNameCaseInsensitive, since your class property names and json property names differ. In Newtonsoft insensetivity is true by default.
var options = new JsonSerializerOptions { WriteIndented = true, PropertyNameCaseInsensitive = true};
JsonSerializer.Deserialize<...>(json, options)

