1

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.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
S. Koshelnyk
  • 478
  • 1
  • 5
  • 20

2 Answers2

3

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

Bill
  • 173
  • 1
  • 8
3

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);
Christos
  • 53,228
  • 8
  • 76
  • 108
  • `var responseCountries = JsonConvert.DeserializeObject>(content);` worked for me – S. Koshelnyk Jun 04 '17 at 19:00
  • @S.Koshelnyk Yeap it needs `DeserializeObject`. Thanks ! – Christos Jun 04 '17 at 19:06
  • Looks like Newtonsoft.Json will deserialize to a Collections.Generic.List if you provide IEnumerable as a generic type argument. IMO, you should just say `DeserializeObject>` for clarity and performance. – Rikki Gibson Jun 04 '17 at 19:39