Android
Unity
VR
daydream

UnityのJsonUtilityでJSON配列を処理する

More than 1 year has passed since last update.


本Qiitaについて

JSONの配列をJsonUtilityで処理する方法について記載


関連Qiita


JsonUtility

{[

{a:11,b:12},
{a:21,b:22},
{a:31,b:32},
]}

は処理できない。

{Items:[

{a:11,b:12},
{a:21,b:22},
{a:31,b:32},
]}

は処理できる。


Livedoorのお天気WebAPIを使ってサンプルを作る

会津若松の天気のJSON

http://weather.livedoor.com/forecast/webservice/json/v1?city=070030

"forecasts" :の配列を取得し格納してみる

JsonHelper.cs

using System;

using UnityEngine;
using System.Collections;

public static class JsonHelper
{
public static T[] FromJson<T>(string json)
{
Wrapper<T> wrapper = UnityEngine.JsonUtility.FromJson<Wrapper<T>>(json);
return wrapper.forecasts;
}

[Serializable]
private class Wrapper<T>
{
public T[] forecasts;
}
}

RestClient.cs

using UnityEngine;

using System.Collections;
using UnityEngine.Networking;
using System.Text;

[System.Serializable]
public class tenki
{
public string dateLabel;
public string telop;
public string date;
}

public class RestClient : MonoBehaviour {

public tenki[] tenkiInstance;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
if (Input.GetKeyUp("g"))
{
Debug.Log ("GET");
StartCoroutine(Get("http://weather.livedoor.com/forecast/webservice/json/v1?city=070030"));
}
}

public IEnumerator Get (string url) {
Debug.Log ("GET");

var request = new UnityWebRequest();
request.downloadHandler = new DownloadHandlerBuffer();
request.url = url;
request.SetRequestHeader("Content-Type", "application/json; charset=UTF-8");
request.method = UnityWebRequest.kHttpVerbGET;
yield return request.Send();

if(request.isError) {
Debug.Log(request.error);
}
else {
if (request.responseCode == 200) {
Debug.Log ("success");
Debug.Log ("--------------------------------");
Debug.Log(request.downloadHandler.text);
Debug.Log ("--------------------------------");
tenkiInstance = JsonHelper.FromJson<tenki>(request.downloadHandler.text);

for (int i = 0; i < tenkiInstance.Length; i++) {
Debug.Log (tenkiInstance [i].dateLabel);
Debug.Log (tenkiInstance [i].telop);
Debug.Log (tenkiInstance [i].date);
}
} else {
Debug.Log ("failed");
}
}
}
}


ToDo

入れ子の配列の処理.