UnityでJsonデータをあつかう
約1秒後に自動的にリダイレクトします。切り替わらない場合はリンクをクリックしてください。
手順概要
I、MiniJsonダウンロード→Pluginフォルダーに取り込む
II、処理スクリプトの記述(Using,Json要求、Json受け取り、Unityでの表示)
だいたいこんな感じです、今回はサーバ側は数年前に稼働していた(現在休止中)のレンタルサーバ上
にあるMysql+PHPで構築されたサーバ側のシステムを利用します。(URLは伏せます)
1、それでは、まずはMiniJsonをダウンロードしましょう。DownLoad Gistボタンをおす
Unity3D: MiniJSON Decodes and encodes simple JSON strings. Not intended for use with massive JSON strings, probably < 32k preferred. Handy for parsing JSON from inside Unity3d.
解凍したMiniJSON.cs.csをUnity側で「Plugins」フォルダーを作成しそこに取り込んでおきましょう。
2、using にSystem.Collections.Generic、MiniJSONを追加します
using UnityEngine; using System.Collections; using System.Collections.Generic; using MiniJSON;
コールーチンでJson処理部分を呼び出します
wwwFormを作ってAddFieldしてphp側に渡すパラメータを設定します
ここではphp側でgiveMeThisIDInfoと記述してあるパラメーターにTest2.idParamaterをセットしています。あとはwwwでphpのURLとFormにセットしたFieldを投げると結果が帰ってきます。
帰ってきたら、Jsonでパースし各の要素をForEachで抜き出してguigui11〜guigui44のGuiTextにセットするだけです。
void Start () { StartCoroutine("GetJSON"); } IEnumerator GetJSON(){ WWWForm wwwForm = new WWWForm (); wwwForm.AddField("giveMeThisIDInfo" , test2.idParamater); // WWW www = new WWW("http://yahhoo.com/getUserDataById2.php",wwwForm); yield return www; // error if(!string.IsNullOrEmpty(www.error)){ Debug.LogError(string.Format("Error ", www.error)); yield break; } Debug.Log ("Recive Data = " + www.text); // string json = www.text; // Json Parse IList zentai = (IList)Json.Deserialize(json); foreach(IDictionary youso in zentai){ //string name = (string)person["name"]; string name = (string)youso["Read_Name"]; guigui11.text=name; string nendai = (string)youso["Read_Nendai"]; guigui22.text=nendai; string danzyo = (string)youso["Read_danzyo"]; guigui33.text=danzyo; string comment = (string)youso["Read_Comment"]; guigui44.text=comment; } }
phpでの処理部分はこんな感じ
function create() { if (isset($_POST["giveMeThisIDInfo"])){ // Put parameters into local variables $uketoriID = $_POST["giveMeThisIDInfo"]; $stmt = $this->db->prepare('SELECT SQL statement'); $stmt->bind_param("i",$p1); $p1=$uketoriID; $stmt->execute(); // Return unlock code, encoded with JSON $stmt->bind_result($Name,$Nendai,$danzyo,$chiiki,$hobby,$Comment); $result = array(); while ($stmt->fetch()){ $result[] = array( 'Read_Name'=> $Name ,'Read_Nendai'=> $Nendai ,'Read_danzyo' => $danzyo ,'Read_chiiki' => $chiiki , 'Read_hobby' => $hobby , 'Read_Comment' => $Comment ); } sendResponse(200, json_encode($result)); $stmt->close(); } //return true; // } }
結果はこんな感じ