Silverlight-Read Formatted Json Data on Server

Json data is one kind of lightweight data interchange formats. It is more efficient to deliver data than XML. Therefore, it is can be used in silverlight to get data more quickly and reduce sent amount of characters. In this post, I will talk about how to serialize one class to Json data and sent to Silverlight.

Create a new general processing program page “GetJson.ashx” on client. Use WriteObject() of DataContractJsonSerialize class to serialize to Json DataSet. Then, use ReadObject() to restore Json data to class. Next, use WebRequest to download data in silverlight.

Firstly, create a new silverlight application. Then add two class City.cs (several propertis contained) and Cities.cs (one property is List assembly of City class) on sever and silverlight.

    public class City

    {

        private string _CityName;

        private string _State;

        public string State

        {

            get { return _State; }

            set { _State = value; }

        }

        public string CityName

        {

            get { return _CityName; }

            set { _CityName = value; }

        }

    }

    public class Cities

    {   

        private List<City> _CityList;

        public List<City> CityList

        {

            get { return _CityList; }

            set { _CityList = value; }

        }

    }

Then, create a new general processing program page “GetJson.ashx” on server. Add the following code to instantiated several city objects and turn to Json data. Note: we need to add System.Runtime.Serialization.dll individually.

    ///<summary>

    ///GetJson Summary

    ///</summary>

    public class GetJson : IHttpHandler

    {

        public void ProcessRequest(HttpContext context)

        {

            //Step 1

            //Format Cities Class to Json String

            string JsonString = ToJsonString(GetCities());

            context.Response.ContentType = “text/plain”;

            context.Response.Write(JsonString);

        }

        private Cities GetCities()

        {

            //Instantiated String Data Group

            Cities cities = new Cities();

            cities.CityList = new List<City>()

            {

                new City(){ CityName=“New York”, State=“New York”},

                new City(){ CityName=“Los Angeles”, State=“California”},

                new City(){ CityName=“Chicago”, State=“Illinois”},

                new City(){ CityName=“Huston”, State=“Texas”},

                new City(){ CityName=“Philadelphia”, State=“Pennsylvania”}

            };

            return cities;

        }

        // Serialize Object Class to Json String

        public string ToJsonString(object ToJsonObject)

        {

            using (MemoryStream ms = new MemoryStream())

            {

                DataContractJsonSerializer serializer =

                    new DataContractJsonSerializer(ToJsonObject.GetType());

                serializer.WriteObject(ms, ToJsonObject);

                StringBuilder sb = new StringBuilder();

                sb.Append(Encoding.UTF8.GetString(ms.ToArray()));

                return sb.ToString();

            }

        }

        public bool IsReusable

        {

            get

            {

                return false;

            }

        }

    }

Run GetJson.ashx and then we can get Json as following:

{“CityList”:[{“CityName”:“New York”, State=“New York”},

{“CityName”:“Los Angeles”, State=“California”},

{“CityName”:“Chicago”, State=“Illinois”},

{“CityName”:“Huston”, State=“Texas”},

{“CityName”:“Philadelphia”, State=“Pennsylvania”}]}

Add System.ServiceModel.Web.dll and System.Runtime.Serialization.dll firstly in silverlight and add the following code to call string which is gotten by general appication page. Then, deserialize it to class.

        public MainPage()

        {

            InitializeComponent();

            //Step 2

            // Call Json Data Stream Getting by http://localhost:2598/GetJson.ashx

            Uri endpoint = new Uri(http://localhost:2598/GetJson.ashx&#8221;);

            WebRequest request = WebRequest.Create(endpoint);

            request.Method = “POST”;

            request.ContentType = “application/x-www-form-urlencoded”;

            request.BeginGetResponse(new AsyncCallback(ResponseReady), request);

        }

        private void ResponseReady(IAsyncResult asyncResult)

        {

            WebRequest request = asyncResult.AsyncState as WebRequest;

            WebResponse response = request.EndGetResponse(asyncResult);

            //Step 3

            //Call UI Thread to Update DataGrid

            this.dataGrid1.Dispatcher.BeginInvoke(()=>{

                this.dataGrid1.ItemsSource =

                    (Deserialize<Cities>(response.GetResponseStream()) as Cities).CityList;

            });

        }

        //Deserialize Json String Stream to Object

        public static T Deserialize<T>(Stream stream)

        {

            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));

            return (T)serializer.ReadObject(stream);

        }

Two Components Recommend:

Spire.Doc, is used to operate MS Word document for .Net and Silverlight, including basic manipulations (generate, open, edit documents), mail merge and other Word functions manipulations.

Spire.XLS, is used to operate MS Excel for .NET and Silverlight, including basic manipulations (generate, open, edit files), chart creation and data exporting.

Advertisements

3 thoughts on “Silverlight-Read Formatted Json Data on Server

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s