參考文章:https://utf-8.live/default/unity-restful-api.html
? ? ? ? ? ? ? ??http://www.xuanyusong.com/archives/4367
Unity 端基本都是通過調(diào)用后端 Http 接口解析 Json 字符串方式跟后端交互,大多使用封裝好的 WWW 類或者 WWWform 調(diào)用后端接口,使用起來非常簡(jiǎn)單方便埃元,但是 WWW 直接調(diào)用 API 默認(rèn)發(fā)起的請(qǐng)求方法是 GET 請(qǐng)求。
如果我們傳輸?shù)氖且粋€(gè) json 字符串:
// Get the latest webcam shot from outside "Friday's" in Times Square
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
? ? public string url = "https://api.com/save";
? ? IEnumerator Start() {
? ? ? ? // 創(chuàng)建一個(gè)字典設(shè)置 key value
? ? ? ? Dictionary Headers = new Dictionary ();?
? ? ? ? Headers.Add ("Content-Type", "application/json");
? ? ? ? // 請(qǐng)求的Json數(shù)據(jù)
? ? ? ? Dictionary Dict = new Dictionary ();
? ? ? ? Dict ["name"] = "ben";
? ? ? ? Dict ["age"] = "18";
? ? ? ? string data = Json.Serialize (Dict);
? ? ? ? // 轉(zhuǎn)字節(jié)
? ? ? ? byte[] data;?
? ? ? ? data = System.Text.UTF8Encoding.UTF8.GetBytes (data);
? ? ? ? WWW www = new WWW (url, data, Headers);
? ? ? ? yield return www;
? ? ? ? // TODO DO SOMETHING
? ? }
}
Unity自己的json序列化是不支持字典格式句占,但通過使用Json.net庫(kù),通過http://www.newtonsoft.com/json下載躯嫉,并將bin/net20/Newtonsoft.Json.dll 拖入unity工程即可實(shí)現(xiàn)序列化纱烘。
字典定義:
Dictionary<string,string> a=new Dictionary<string,string>();
Dictionary里的每一元素都由keyvalue組成,key和value祈餐,通過一個(gè)key讀取一個(gè)value擂啥。
實(shí)現(xiàn)方式:using Newtonsoft.Json
public class Test : MonoBehaviour {
void Start()
{
Product product = new Product();
product.dic ["字典key"] = "字典Value";
product.name="我是雨松MOMO";
string json = JsonConvert.SerializeObject(product);
Product m = JsonConvert.DeserializeObject(json);
Debug.Log (json);
Debug.Log (m.name);
}
public class Product
{
public string name;
public Dictionary dic=new Dictionary();
}
}