C# System.Text.Json Can't deserialize response from open sky api. My DTO model doesn't fit I have response body like this and i can't desearilize it to c# dto model:
{
"time": 1677521877,
"states": [
[
"a2e5ec",
"SKW3744",
"United States",
1677521876,
1677521876,
-122.31,
47.3658,
1447.8,
false,
102.38,
179.42,
7.48,
null,
1280.16,
null,
false,
0
]
]
}
This is my dto model for this response:
public class RootObjectOfFlightStatus
{
[JsonPropertyName("time")]
public long Time { get; set; }
[JsonPropertyName("states")]
public List<List<FlightStatusOpenSkyDto>>? States { get; set; }
}
public class FlightStatusOpenSkyDto
{
[JsonPropertyName("0")]
public string? Icao24 { get; set; }
[JsonPropertyName("1")]
public string? Callsign { get; set; }
[JsonPropertyName("2")]
public string? OriginCountry { get; set; }
[JsonPropertyName("3")]
public int? TimePosition { get; set; }
[JsonPropertyName("4")]
public int? LastContact { get; set; }
[JsonPropertyName("5")]
public float? Longitude { get; set; }
[JsonPropertyName("6")]
public float? Latitude { get; set; }
[JsonPropertyName("7")]
public float? BaroAltitude { get; set; }
[JsonPropertyName("8")]
public bool? OnGround { get; set; }
[JsonPropertyName("9")]
public float? Velocity { get; set; }
[JsonPropertyName("10")]
public float? TrueTrack { get; set; }
[JsonPropertyName("11")]
public float? VerticalRate { get; set; }
[JsonPropertyName("12")]
public int[]? Sensors { get; set; }
[JsonPropertyName("13")]
public float? GeoAltitude { get; set; }
[JsonPropertyName("14")]
public string? Squawk { get; set; }
[JsonPropertyName("15")]
public bool? Spi { get; set; }
[JsonPropertyName("16")]
public int? PositionSource { get; set; }
[JsonPropertyName("17")]
public int? Category { get; set; }
}`
`RootObjectOfFlightStatus? flightStatusOpenSkyDto = JsonSerializer.Deserialize<RootObjectOfFlightStatus>(here is respone);
and I get
flightStatusOpenSkyDto
value always null. I'm short of ideas what is wrong here. Could you please help?
I suggest the trouble is in this line of code.
public List<List<FlightStatusOpenSkyDto>>? States { get; set; }
I tried here several options but still get the same result:
List<FlightStatusOpenSkyDto[]>? States,
FlightStatusOpenSkyDto[][]? States
Your FlightStatusOpenSkyDto
class is expecting there to be JSON in the form of "0": "value", "1": "another value"...
which doesn't match. Instead, you are going to have to either write your own custom converter or you could simply use object
instead. For example:
public class RootObjectOfFlightStatus
{
...
[JsonPropertyName("states")]
public List<List<JsonElement>> States { get; set; }
}
Then you can do something like this:
var result = JsonSerializer.Deserialize<RootObjectOfFlightStatus>(Json);
var icao24 = result.States[0][0].GetString();
var timePosition = result.States[0][3].GetInt32();