Search This Blog

Monday, 11 July 2016

JSON Example

MainActivity.CS:-

using Android.App;
using Android.Widget;
using Android.OS;
using System.Collections.Generic;

namespace JsonServies
{
[Activity (Label = "JsonServies", MainLauncher = true, Icon = "@mipmap/icon")]
public class MainActivity : Activity
{
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);

// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);

ListView lstPersons = (ListView)FindViewById (Resource.Id.lstPersons);

Services obj = new Services ();
obj.GetMovieData (this,lstPersons);
}
}
}


Main.AXML:-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ListView
        android:id="@+id/lstPersons"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>


Movies.CS:-

using System;
using System.Collections.Generic;

namespace JsonServies
{
public class Movie
{
public Movie ()
{
}

public string name { get; set; }
public string height { get; set; }
public string mass { get; set; }
public string hair_color { get; set; }
public string skin_color { get; set; }
public string eye_color { get; set; }
public string birth_year { get; set; }
public string gender { get; set; }
public string homeworld { get; set; }
public List<string> films { get; set; }
public List<string> species { get; set; }
public List<object> vehicles { get; set; }
public List<object> starships { get; set; }
public string created { get; set; }
public string edited { get; set; }
public string url { get; set; }
}
}



Services.CS:-

using System;
using System.Net;
using Newtonsoft.Json;
using System.Collections.Generic;
using Android.Widget;
using Android.App;

namespace JsonServies
{
public class Services
{
List<Movie> objList;
public Services ()
{
}
public void GetMovieData(Activity act, ListView lstMovies){

WebClient objWebClient = new WebClient ();
objWebClient.DownloadStringCompleted += async
delegate(object sender, DownloadStringCompletedEventArgs e) {
Activity.RunOnUiThread(() => {
List<Movie> objList=JsonConvert.DeserializeObject<List<Movie>>(e.Result.ToString());
});
};
objWebClient.DownloadStringAsync (new Uri ("http://swapi.co/api/people/2/"));
}
}
}





No comments:

Post a Comment