首先是一個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請求並返回數據的過程。