どこまでも自由な日々

パソコン初心者主婦のブログです。

UnityでネストされたJSONデータを読み込む

データの読み込みにはJSONObjectを利用することにしました。

JSONObject - Unify Community Wiki

 

こちらのありがたいAssetはResourcesフォルダにインポートしたらそれでOK。

次は元になるJSONデータ・URLを用意。

{"coord":{"lon":100,"lat":28},"sys":{"message":0.0173,"country":"CN","sunrise":1433283805,"sunset":1433333572},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01d"}],"base":"stations","main":{"temp":291.042,"temp_min":291.042,"temp_max":291.042,"pressure":659.73,"sea_level":1016.79,"grnd_level":659.73,"humidity":36},"wind":{"speed":0.75,"deg":244.002},"clouds":{"all":0},"dt":1433303679,"id":6643967,"name":"Gezan","cod":200} 

 元データ↑WorldWetherAPIより。

ところでみんな目視でデータ見るときどうしてるんだろう。

私はVisualJSONをとりあえず入れてるけど結局ブラウザの整形機能使うよね。

 

weatherのところが一度[ ]で囲まれてる。

前もこういうやつでハマった。

 

     IEnumerator Download() {
        WWW url = new WWW("http://api.openweathermap.org/data/2.5/weather?lat=28&lon=100");//JSONデータのURL

        yield return url;

        JSONObject json = new JSONObject(url.text);
//        Debug.Log(www.text); //生JSONデータ

 

      string weather = json.GetField ("base").str;

        Debug.Log(www.text); //ネストされてないデータ

        JSONObject arr = json.GetField("weather");
        Debug.Log ("一回目。天気のリストは" + arr);
        JSONObject arr2 = arr[0];
        Debug.Log ("まるっと取り出し。" + arr2);
        JSONObject result = arr2.GetField ("main");
        Debug.Log ("お天気は"+ result);  
    }

 

わーいできた!ヽ(=´▽`=)ノ

小一時間ハマったくせに超カンタンに取出せたよ。