Korken55 Korken55 - 3 months ago 17
JSON Question

Xamarin store multiple data in Variable

I have my code, where i fetch data from a url and parse that data with json.

public async void GetItems()
{
HttpResponseMessage response = new HttpResponseMessage();
HttpClient httpclient = new HttpClient();
Uri uri = new Uri("URL");

response = await httpclient.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var JsonContent = await response.Content.ReadAsStringAsync();

JArray jArray = JArray.Parse(JsonContent);

foreach (var data in jArray)
{
var latitude = data["latitude"];
Console.WriteLine(latitude);
}

}
}


in this code I get all my data and print them into the console.

I have a class with the variables i want to set

public class FetchedObjects
{
public string name { get; set; }
public double latitude { get; set; }
public double longitude { get; set; }

}


How can I store each data from my jArray into these variables? I want to have access to these from my ios or android project.

EDIT
I have some values in json, which are null. How can i handle these, while creating the list? My App crashes, it says :


Error setting value to 'valuename' on 'App.FetchedObjects'

Answer

Try it code:

 List<FetchedObjects> list = jArray.ToObject<List<FetchedObjects>>();

Edit

in pcl library create class:

 public class YourClass
 {
    public async  Task<List<FetchedObjects>> GetItems()
    {
       ....
       if(jArray != null)
       {
          List<FetchedObjects> list = jArray.ToObject<List<FetchedObjects>>();
          return list;
       }
       else
       {
          return null;
       }  
    ...
 } 

Add reference to pcl library in your ios and android projects and Use class YourClass