0.PHP端封装Json数据的格式,如下:
{
"code": 200,
"desc": "成功",
"data": {
"state": 1,
"distance": "距离目标115米"
}
}
1.首先定义个MessagePosition类,声明经度纬度字段。
using UnityEngine;
using System.Collections;
/// <summary>
/// 2016/04/25 1.经度纬度信息
/// </summary>
public class MessagePosition
{
//public int userID;
public string lat1;
public string lng1;
}
2.然后定义HttpTest类实现向PHP服务器发送和解析Json格式数据。
using UnityEngine;
using System.Collections;
using LitJson;
using System.Text;
/// <summary>
/// 2016/04/25 2.实现Unity3d通过Http协议 向PHP服务器发送和解析Json格式数据 的测试类
/// </summary>
public class HttpTest : MonoBehaviour
{
// Awake()
void Awake()
{
StartCoroutine(InitMessagePositionJson());//调用协同程序 进行数据交互
}
//利用协同程序 发送和解析Json数据到PHP服务器
IEnumerator InitMessagePositionJson()
{
#region 发送Json数据
MessagePosition msPosition = new MessagePosition();
//msPosition.userID = 1;
msPosition.lat1 = "121.4441";
msPosition.lng1 = "31.345991";
WWWForm form = new WWWForm();
form.AddField("lat1", msPosition.lat1);
form.AddField("lng1", msPosition.lng1);
WWW www = new WWW("http://127.0.0.1/index.php?c=User&a=distance", form);
#endregion
#region 请求Json数据
while (!www.isDone)
{
Debug.Log("wait...");
}
yield return www;
if (www.error != null)
{
Debug.LogError(www.error);
}
#endregion
#region 解析Json数据
else
{
//Debug.Log(www.text);//打印Json数据内容的
JsonData jsonData = JsonMapper.ToObject(www.text);
Debug.Log(jsonData["code"].ToString());
Debug.Log(jsonData["desc"].ToString());
if (jsonData["data"] != null)
{
Debug.Log(jsonData["data"]["state"].ToString());
Debug.Log(jsonData["data"]["distance"].ToString());
}
}
#endregion
}
}