S. Koshelnyk
S. Koshelnyk

Reputation: 506

Parsing data from json in C#

I successfully got data to var content The code how I did it:

public async void FetchAsync()
{
    var client = new RestClient("http://api.locopal.com");
    var request = new RestRequest("/countries", Method.POST);
    var response = client.Execute(request);
    var content = response.Content;
    var responseCountries = JArray.Parse(JObject.Parse(content)[""].ToString());
}

But in line: var responseCountries = JArray.Parse(JObject.Parse(content)[""].ToString()); I got An unhandled exception occured. This is the data from var content: enter image description here

Countries from here need to be write down to list.

Upvotes: 1

Views: 883

Answers (2)

Christos
Christos

Reputation: 53958

You could declare a class like the following

public class Country
{
    [JsonProperty("id")]
    public int Id { get; set; } 

    [JsonProperty("nicename")]
    public string Name { get; set; }
}

and then deserialize the json as below:

var responseCountries = JsonConvert.DeserializeObject<IEnumerable<Country>>(content);

Upvotes: 3

Bill
Bill

Reputation: 183

You should deserialize the JSON into an object. You can create a POCO object with the properties from the JSON.

Example:

public class Country
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("nicename")]
    public string Name { get; set; }
}

Edit: Follow same casing as in JSON

Upvotes: 3

Related Questions