シヴァのブログ

UnityやUE4や趣味とかいろいろ...

Unityで天気情報取得(JSON、MiniJSON)

天気の情報を取得するためには、
Jsonを使う方法がよく書かれているので同じ方法を使います。
今回の内容は以下の2つ。

・天気の情報を取得し、ファイルに書き込む
・書き込んだJSON形式のファイルの値を取得


まず、簡単なメモ

Jsonの形式で書かれたファイルを読み込む方法。
qiita.com
JSONのデータをUnity側でデバッグログで出力。

{
    "name": "phi",
    "age": 26,
    "bloodType": "O"
}
Debug.Log ((string)json["name"]);
Debug.Log ((long)json["age"]);
Debug.Log ((string)json["bloodType"]);

f:id:shivaT:20150530053537p:plain
次。
天気情報をJson形式で取得する方法。
qiita.com


・東京の天気取得(メモ)

var url = "http://api.openweathermap.org/data/2.5/weather?q=Tokyo,jp;

・ファイルにテキスト書き込み
※「StreamWriter」の第2パラメータは、
既存ファイルが存在する場合の振る舞いを示す(false:上書き、true:追記)

var sw : StreamWriter;
sw = new StreamWriter("ファイルパス", false);
sw.WriteLine(req.text);
sw.Close();


・書き込み方について(メモ)

sw.Write( "hogehoge" );     // 文字列の書き込み
sw.Write( 123 );            // 数値の書き込み
sw.Write( "\r\n" );         // 改行文字の書き込み
sw.WriteLine( "hogehoge" ); // 文字列の書き込み(1行分)

まとめ

天気の情報を取得し、ファイルに書き込む

#pragma strict
import System.IO;

function Start () {
	var url = "http://api.openweathermap.org/data/2.5/weather?q=Tokyo,jp";
	var wwwForm:WWWForm = new WWWForm();
	
	var name="Tokyo";
	wwwForm.AddField("name", name);
	
	var req : WWW = new WWW(url,wwwForm);
	yield req;
	if(req.error != null || req.text == ""){
		Debug.Log(req.error);
	}else{
		Debug.Log(req.text);
		var sw : StreamWriter;
		sw = new StreamWriter("/Users/shiva/Desktop/Unity_chan/test_unitycan/Assets/Resources/sample.json", false);
		sw.WriteLine(req.text);
		sw.Close();
	}
	//メモリ解放
	req.Dispose();
}

function Update () {

}

・書き込まれた「sample.json」の中身

{
	"coord":{
		"lon":139.69,
		"lat":35.69
	},
	"sys":{
		"message":0.5932,
		"country":"JP",
		"sunrise":1432927640,
		"sunset":1432979410
	},
	"weather":[{
		"id":803,
		"main":"Clouds",
		"description":"broken clouds",
		"icon":"04n"
	}],
	"base":"stations",
	"main":{
		"temp":294.698,
		"temp_min":294.698,
		"temp_max":294.698,
		"pressure":1008.06,
		"sea_level":1013.03,
		"grnd_level":1008.06,
		"humidity":79
	},
	"wind":{
		"speed":2.06,
		"deg":251.505
	},
	"clouds":{
		"all":64
	},
	"dt":1433010788,
	"id":1850147,
	"name":"Tokyo",
	"cod":200
}

書き込んだJSON形式のファイルの値を取得

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using MiniJSON;

public class json : MonoBehaviour {

	// Use this for initialization
	void Start () {
		var textAsset = Resources.Load ("sample") as TextAsset;
		var json = textAsset.text;
		//(1階層目)
		var jsonData = MiniJSON.Json.Deserialize(json) as Dictionary<string, object>;
		//(2階層目)
		var main = jsonData["main"] as Dictionary<string, object>;
		var weather = (IList)jsonData["weather"];
		var coord = jsonData["coord"] as Dictionary<string, object>;
		var wind = jsonData["wind"] as Dictionary<string, object>;
		var sys = jsonData["sys"] as Dictionary<string, object>;
		//(3階層目)
		var weather_0 = (IDictionary)weather[0];

		Debug.Log ((double)main["temp"]);//気温
		Debug.Log ((double)main["temp_min"]);//最低気温
		Debug.Log ((double)main["temp_max"]);//最高気温
		Debug.Log ((long)weather_0["id"]);//街のID
		Debug.Log ((string)weather_0["description"]);//天気の概要
		Debug.Log ((string)weather_0["icon"]);//アイコンID
		Debug.Log ((string)weather_0["main"]);//天気
		Debug.Log ((double)coord["lat"]);//緯度
		Debug.Log ((double)coord["lon"]);//経度
		Debug.Log ((double)main["pressure"]);//気圧
		Debug.Log ((long)main["humidity"]);//湿度
		Debug.Log ((double)wind["speed"]);//風速
		Debug.Log ((string)jsonData["name"]);//都市名
		Debug.Log ((string)sys["country"]);//国名
		Debug.Log ((long)sys["sunrise"]);//日の出時間
		Debug.Log ((long)sys["sunset"]);//日没時間
	}
	
	// Update is called once per frame
	void Update () {
	
	}
}

f:id:shivaT:20150531033312p:plain