I have the following problem: I am a C# beginner and I want to create a weather app using the OpenWeatherApi. The response of the api looks like this (it´s just an example): [ { "name": "London", "lat": 51.5085, "lon": -0.1257, "country": "GB" }, I want to get the lat and lon values. My C# code looks like this:
public class CoordinatesResponse
{
public double Lat { get; set; }
public double Lon { get; set; }
}
private static string _coordinatesResponse;
static void ExtractCoordinatesFromJson()
{
CoordinatesResponse coordinatesresponse = JsonConvert.DeserializeObject<CoordinatesResponse>(_coordinatesResponse);
Console.WriteLine(coordinatesresponse.Lat);
Console.WriteLine(coordinatesresponse.Lon);
}
My error is the following:
Unhandled exception. Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'WeatherApp.CoordinatesResponse' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
What do I wrong?
CodePudding user response:
Your problem is in the type. Been an array, you must use List<CoordinatesResponse>
:
static void ExtractCoordinatesFromJson()
{
var coordinatesresponses = JsonConvert.DeserializeObject<List<CoordinatesResponse>>(_coordinatesResponse);
foreach (var coordinatesresponse in coordinatesresponses)
{
Console.WriteLine(coordinatesresponse.Lat);
Console.WriteLine(coordinatesresponse.Lon);
}
}