'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?



Solution 1:[1]

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);
    }
}

Solution 2:[2]

To solve the issue " Cannot deserialize the current JSON array (e.g. [1,2,3])" Follow the steps:

  1. Go to any website that convert JSON to C# (e.g. https://json2csharp.com/).

  2. Paste your JSON data in the JSON section and click on generate C# link button.

  3. It will generate the object to deserialize the json array. e.g. JsonDataService myData = JsonConvert.DeserializeObject(json);

  4. The above object can be used to manipulate the JSON string object.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Victor
Solution 2