42
38

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UnityからC#でJSONのWebAPIをコールして解析する方法

Last updated at Posted at 2014-03-13

HTTP通信はWWWクラスでやる。
非同期呼び出しなのでStartCoroutineで呼び出す。

UnityでJSONを解析する方法はいくつかあるが

  1. LitJson
  2. JSONObject
    を試してみた。

LitJsonはユーザー定義のデータオブジェクトにマッピングする方式。
JSONObjectは連想配列のような汎用オブジェクトにマッピングする方式。
簡単な形式のJSONならJSONObjectで、複雑な形式のJSONならLitJsonがいいんじゃないかと思う。

以下コード抜粋

JSONWebAPICallSample.cs
using LitJson;
//JSONObjectはnamespaceなしなのでusing不要

public class JSONWebAPICallSample : MonoBehaviour {
   void Start() {
        StartCoroutine(Download());
    }
    IEnumerator Download() {
        WWW www = new WWW("http://localhost/abc.txt");
    
        yield return www;

        //LitJSONで解析
        SampleData[] datas = JsonMapper.ToObject<SampleData[]>(www.text);
        foreach (var d in datas) {
            Debug.Log("d.id " + d.id);
            Debug.Log("d.first " + d.first);
            Debug.Log("d.second " + d.second);
            Debug.Log("d.third " + d.third);
    
        }

        //JSONObjectで解析
        JSONObject json = new JSONObject(www.text);
        for (int i = 0; i < json.Count; i++) {
            JSONObject json1 = json[i];
            JSONObject id = json1.GetField("id");

            JSONObject first = json1.GetField("first");
            Debug.Log("json id.str=" + id.str);
            Debug.Log("json id=" + id);
            string a = "PPPP";
            Debug.Log("json a=" + a);
            Debug.Log("json id=" + id);
            Debug.Log("json first=" + first);
        }
	        
        Debug.Log(www.text);
    }
}
[System.Serializable]
public class SampleData {
    public string id;
    public int first;
    public int second;
    public int third;
}
[abc.txt]
[
	{
	    "id": "id1",
	    "first": 1, 
	    "second": 2, 
	    "third": 3
	},
	{
	    "id": "id2",
	    "first": 11, 
	    "second": 22, 
	    "third": 33
	}
]
NGUI for Unity-【電子書籍】

NGUI for Unity-【電子書籍】
価格:1,569円(税5%込、送料込)

42
38
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
42
38

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?