Tuesday, February 4, 2014

Consume data from REST service, Serialize / Deserialize the json string in Windows Phone 8 Apps


CommonClass:
Below are the Microsoft built-in Generic Methods to serialize / deserialize JSON data in Windows Phone 8:
        public static T DeserializeJSon<T>(string jsonString)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T obj = (T)ser.ReadObject(stream);
            return obj;
        }

        public static string SerializeToJson<T>(T obj)
        {
            MemoryStream stream = new MemoryStream();
            DataContractJsonSerializer jsonSer =
            new DataContractJsonSerializer(typeof(T));
            jsonSer.WriteObject(stream, obj);
            stream.Position = 0;
            StreamReader sr = new StreamReader(stream);
            var json = sr.ReadToEnd();
            return json;
        }


Now, to get the data from REST and deserialize the result json, back to object in Windows Phone 8:

        public static void GetDataAsync<T>(string restServiceMethodUrl)
        {
            var jsonResult = string.Empty;
            var webClient = new WebClient();

            webClient.DownloadStringAsync(new Uri(restServiceMethodUrl));
            webClient.DownloadStringCompleted += (s, e) =>
            {
                if (e.Error != null)
                {
                    jsonResult = e.Result.ToString();
                    var objActualData = DeserializeJSon<TestViewModel>(jsonResult);
                }
            };
        }


To post / get data basis with input parameters, below is the method in Windows Phone 8:

        public static void PostDataAsync<T>(Uri uri, ObjectAsInput obj)
        {
            var jsonResult = string.Empty;
            var webClient = new WebClient();
            var jsonDataInput = SerializeToJson<ObjectAsInput >(obj);

            if (!string.IsNullOrEmpty(jsonDataInput))
            {
                webClient.Headers["Content-Type"] = "application/json; charset=utf-8";
                webClient.UploadStringAsync(uri, jsonDataInput);
                webClient.UploadStringCompleted += (s, e) =>
                {
                    if (e.Error != null)
                    {
                        jsonResult = e.Result.ToString();
                        var actualData = DeserializeJSon<TestViewModel>(jsonResult );
                    }

                };
            }
        }

        

No comments:

Post a Comment