• 【转】Unity利用WWW http传输Json数据


    http://blog.csdn.net/h570768995/article/details/50386935


    首先去下载LitJson.dll,放在Plugins 目录下;

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

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

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

    为了能对应该Json格式,我们需要定义如下类:
    [csharp] view plain copy
     
    1. public class MessageJson  
    2. {  
    3.     public int intValue;  
    4.     public long longValue;  
    5.     public string stringValue;  
    6.     public byte byteValue;  
    7.     public double doubleValue;  
    8. }  
    然后在方法中声明该类,接着将其映射为Json格式:
    [csharp] view plain copy
     
    1. MessageJson msgJson = new MessageJson();  
    2. msgJson.intValue = 20;  
    3. msgJson.longValue = 10000000000000L;  
    4. msgJson.stringValue = "chenhao";  
    5. msgJson.byteValue = (byte)msgJson.intValue;  
    6. msgJson.doubleValue = 3153456.125651;  
    7.   
    8. string jsonDataPost = JsonMapper.ToJson(msgJson);  


    如此将该数据传送出去:
    [csharp] view plain copy
     
    1. WWW www = new WWW("http://192.168.1.192:18080/test",Encoding.UTF8.GetBytes(jsonDataPost));  

    接着等待数据,并可以打印出来:

    [csharp] view plain copy
     
    1.        while(!www.isDone)  
    2.         {  
    3.             Debug.Log("wait");  
    4.         }  
    5.         yield return www;  
    6.         if(www.error!=null)  
    7.         {  
    8.             Debug.LogError(www.error);  
    9.         }  
    10.         else  
    11.         {  
    12.             Debug.Log(www.text);  
    13. //取数据1  
    14.             MessageJson msgJsonRecieve = JsonMapper.ToObject<MessageJson>(www.text);  
    15.   
    16.             Debug.Log(msgJsonRecieve.intValue);  
    17.             Debug.Log(msgJsonRecieve.longValue);  
    18.             Debug.Log(msgJsonRecieve.stringValue);  
    19.             Debug.Log(msgJsonRecieve.byteValue);  
    20.             Debug.Log(msgJsonRecieve.doubleValue);  
    21. //取数据2  
    22.             JsonData jsonData = JsonMapper.ToObject(www.text);  
    23.             if (jsonData["stringValue"] != null)  
    24.             {  
    25.                 Debug.Log(jsonData["stringValue"].ToString());  
    26.              }  
    JsonMapper映射可以无视排序问题,它只看“键值对”中的键。
  • 相关阅读:
    【Codeforces Round #645 (Div. 2) A】 Park Lighting
    【Codeforces Round #636 (Div. 3) D】Constant Palindrome Sum
    【Codeforces Round #628 (Div. 2) D】Ehab the Xorcist
    【Codeforces Round #642 (Div. 3)】Constructing the Array
    【LeetCode 85】最大矩形(第二遍)
    scrum例会报告+燃尽图02
    scrum例会报告+燃尽图01
    版本控制报告
    Scrum立会报告+燃尽图 07
    Scrum立会报告+燃尽图 05
  • 原文地址:https://www.cnblogs.com/mimime/p/5998710.html
Copyright © 2020-2023  润新知