Wp7客户端与Webservice的数据传输,json的序列化与反序列化

首先是一个json序列化与反序列化的的帮助类(不记得是看博客园哪个大神的了。。):

public class JsonHelper

    {    

        public static string JsonSerializer<T>(T t)  

        {

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

            MemoryStream ms = new MemoryStream();

            ser.WriteObject(ms, t);

            string jsonString = Encoding.UTF8.GetString(ms.ToArray());

            ms.Close();

            return jsonString;

        }

        public static T JsonDeserialize<T>(string jsonString)

        {

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

            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));

            T obj = (T)ser.ReadObject(ms);

            return obj;

        }

    }

一个实体类:

public class WeatherInfo

    {

        public string CityName { get; set; }

        public string Date { get; set; }

    }

 

服务端代码:

[WebMethod(Description = "返回信息")]

        public string getJson(String city)

        {

            WeatherInfo weather = new WeatherInfo();

            weather.CityName = city;

            weather.Date = Date.Now.ToString();

            string jsonString = JsonHelper.JsonSerializer<WeatherInfo>(weather);

            return jsonString;

        }

客户端代码:

public void GetForecast(string city)

        {

            WebClient client = new WebClient();

            client.OpenReadAsync(new Uri("http://localhost/Weather.asmx/getJson?city=" + city

                + "&time=" + DateTime.Now.ToString("yyyyMMddHHmmss"),UriKind.RelativeOrAbsolute));

            client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);

        }
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)

        {

            try

            {

                XElement xmlWeather;

                xmlWeather = XElement.Load(e.Result);

                WeatherInfo weatherInfo = new WeatherInfo();



                weatherInfo = JsonHelper.JsonDeserialize<WeatherInfo>(xmlWeather.Value);



               

                //Debug.WriteLine(weatherInfo.CityName);



            }

            catch (Exception)

            {

                Deployment.Current.Dispatcher.BeginInvoke(() =>

                {

                    MessageBox.Show("数据获取出错。");

                });

            }

        }

这样就实现了webservice相应wp7app请求并返回数据的过程。

你可能感兴趣的:(webservice)