【一天一個小知識10/20】Unity通過www獲取json文字資訊。
阿新 • • 發佈:2021-10-20
前提:領導要我在unity獲取區域網伺服器的文字資訊。給了一個json的網路文字讓我測試。我對於json以及伺服器比較陌生。就直接去網上找相關的資料。
以下是自己測試的程式碼,沒問題。
測試的網路json格式:
[{"mouth":"1年","y":"300","s":"1"},{"mouth":"2年","y":"500","s":"1"}, {"mouth":"1年","y":"400","s":"2"},{"mouth":"2年","y":"600","s":"2"},{"mouth":"3年","y":"900","s":"1"}, {"mouth":"3年","y":"800","s":"2"},{"mouth":"4年","y":"850","s":"1"},{"mouth":"4年","y":"950","s":"2"}]
網址:https://getman.cn/mock/sensemars/zhexiantu
注意:json需要LitJson外掛
先建一個對應類
(1)類(根據json格式自己改變)
public class MessageJson { public string mouth; public string y; public string s; }
先建一個連線類
(2)類(隨便掛一個物件)
using System.Collections; using System.Collections.Generic; using UnityEngine; using LitJson; using System.Text;using UnityEngine.UI; public class JsonLink : MonoBehaviour { string jsonDataPost; public Text text1; private void Start() { MessageJson msgJson = new MessageJson(); msgJson.mouth = ""; msgJson.y = ""; msgJson.s = ""; jsonDataPost = JsonMapper.ToJson(msgJson); StartCoroutine("Time"); } // Start is called before the first frame update[System.Obsolete] IEnumerator Time() { WWW www = new WWW("https://getman.cn/mock/sensemars/zhexiantu", Encoding.UTF8.GetBytes(jsonDataPost)); while (!www.isDone) { Debug.Log("wait"); } yield return www; if (www.error != null) { Debug.LogError(www.error); } else { Debug.Log(www.text); text1.text = www.text; //取資料1 MessageJson[] msgJsonRecieve = JsonMapper.ToObject<MessageJson[]>(www.text); for (int i = 0; i < msgJsonRecieve.Length; i++) { Debug.Log(msgJsonRecieve[i].mouth); Debug.Log(msgJsonRecieve[i].y); Debug.Log(msgJsonRecieve[i].s); } ////取資料2 (取資料1 和取資料2可以選一個就行) //JsonData jsonData = JsonMapper.ToObject(www.text); //if (jsonData["stringValue"] != null) //{ // Debug.Log(jsonData["stringValue"].ToString()); //} } } }
完畢!