您的位置:首页 > 理论基础 > 计算机网络

Unity利用WWW http传输Json数据

2015-12-23 14:46 465 查看
首先去下载LitJson.dll,放在Plugins 目录下;

LitJson可以从下面的地址获得:http://download.csdn.net/detail/h570768995/9373927

然后我们定义json格式,比如我们需要如下格式:

{"intValue":345,"longValue":345679876,"stringValue":"xiaoxian","byteValue":'v',"doubleValue":345.87}

为了能对应该Json格式,我们需要定义如下类:

public class MessageJson
{
public int intValue;
public long longValue;
public string stringValue;
public byte byteValue;
public double doubleValue;
}
然后在方法中声明该类,接着将其映射为Json格式:

MessageJson msgJson = new MessageJson();
msgJson.intValue = 20;
msgJson.longValue = 10000000000000L;
msgJson.stringValue = "chenhao";
msgJson.byteValue = (byte)msgJson.intValue;
msgJson.doubleValue = 3153456.125651;

string jsonDataPost = JsonMapper.ToJson(msgJson);


如此将该数据传送出去:

WWW www = new WWW("http://192.168.1.192:18080/test",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);
//取数据1
            MessageJson msgJsonRecieve = JsonMapper.ToObject<MessageJson>(www.text);

            Debug.Log(msgJsonRecieve.intValue);
            Debug.Log(msgJsonRecieve.longValue);
            Debug.Log(msgJsonRecieve.stringValue);
            Debug.Log(msgJsonRecieve.byteValue);
            Debug.Log(msgJsonRecieve.doubleValue);
//取数据2
JsonData jsonData = JsonMapper.ToObject(www.text);
            if (jsonData["stringValue"] != null)
            {
                Debug.Log(jsonData["stringValue"].ToString());
             }
JsonMapper映射可以无视排序问题,它只看“键值对”中的键。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: