djklasj dsajdkla
djklasj dsajdkla

Reputation: 81

Reading a json content in Xamarin forms

I am new in Xamarin forms and json and I am using the Newtonsoft.Json to deserialze the data

I am trying to read from a json data to a list of a class name user I created.

I am not sure how to connect the deserialize into a a list of class since after the desrialzation I put it into a var varaible and not to a list of class name users.

will appericate a code example of how to fix my code below:

Thanks.

json looks like this:

[{"Id":"0","userPhone":"000000","userName":"Barak","Conferance_ID":"1"}]

attaching my code:

public async Task<List<User>>  GetUserList(string textBox)
    {
        // Use https to satisfy iOS ATS requirements.
        var client = new HttpClient();
        var response = await client.GetAsync("http://conferencecreating-com.stackstaging.com/UsersWebService.php");
        var responseString = await response.Content.ReadAsStringAsync();
        var JsonObject  = JsonConvert.DeserializeObject (responseString);
           // want to add here how loop the jason object?

    }

this the class I created to inset the data

 public class User
{
    public int ID { get; set; }
    public string userPhone { get; set; }
    public string userName { get; set; }
    public int Conferance_ID { get; set; }
}

Upvotes: 0

Views: 8396

Answers (2)

Yannik
Yannik

Reputation: 1037

Try something like this:

    List<User> Users;
    using (var client = new HttpClient())
       try
       {
           string url = "http://conferencecreating-com.stackstaging.com/UsersWebService.php";
           var response = await client.GetAsync(url);
           response.EnsureSuccessStatusCode();

           var stringResult = await response.Content.ReadAsStringAsync();
           Users = JsonConvert.DeserializeObject<List<User>>(stringResult);
       }
       catch (HttpRequestException httpRequestException)
       {
           Users = null;
       }

Make sure you tell the DeserializeObject which Class/Object you want to match. enjoy!

EDIT: Thanks to the Comment from Sir Rufo I have fixed the Code

Upvotes: 1

Brian Rogers
Brian Rogers

Reputation: 129807

Change this line:

var JsonObject  = JsonConvert.DeserializeObject (responseString);

To this:

var userList = JsonConvert.DeserializeObject<List<User>>(responseString);

To loop over the users, just use a foreach loop like you normally would:

foreach (User user in userList)
{
    ...
}

Upvotes: 3

Related Questions