Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to get Json values which are not in a class using C#?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading