public async void GetWeather(string text) { Windows.Data.Json.JsonObject total_json = await service.GetWeatherItem(text); if (total_json == null) { MessageDialog dialog = new MessageDialog("搜索不到相关城市信息\n请检查输入是否无误"); await dialog.ShowAsync(); return; } StringBuilder message = new StringBuilder(""); if (total_json.GetNamedNumber("showapi_res_code") != 0) { message.AppendLine(total_json.GetNamedString("showapi_res_error")); MessageDialog dialog = new MessageDialog(message.ToString()); await dialog.ShowAsync(); } else { json = total_json.GetNamedObject("showapi_res_body"); current_item.Area = json.GetNamedObject("cityInfo").GetNamedString("c9") + json.GetNamedObject("cityInfo").GetNamedString("c7") + "省" + json.GetNamedObject("cityInfo").GetNamedString("c3") + "市"; current_item.Json = json.GetNamedObject("now"); AllItems.Clear(); for (int i = 1; i <= 7; i++) { AllItems.Add(new WeatherItem(json.GetNamedObject("f" + i))); } } }
// JSONフォーマットの文字列から匿名型データを作る private void LoadData(string json) { // JSONフォーマットの文字列からJsonObjectオブジェクトを作る var data = new Windows.Data.Json.JsonObject(); bool success = Windows.Data.Json.JsonObject.TryParse(json, out data); if (success) { // JsonObjectオブジェクトから画面表示に必要なデータを取り出し、 // 匿名型のオブジェクトに詰め込む Windows.Data.Json.JsonObject weather = data.GetNamedArray("weather", null)?.GetObjectAt(0); Windows.Data.Json.JsonObject main = data.GetNamedObject("main", null); string iconId = weather?.GetNamedString("icon", string.Empty); Data = new { Main = weather?.GetNamedString("main", "(不明)"), Temp = main?.GetNamedNumber("temp", -999), TempMin = main?.GetNamedNumber("temp_min", -999), TempMax = main?.GetNamedNumber("temp_max", -999), Place = data.GetNamedString("name", "(不明)"), IconUrl = iconId != null ? $"http://openweathermap.org/img/w/{iconId}.png" : null, }; } }