前提:领导要我在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
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());
//}
}
}
}
完毕!
手机扫一扫
移动阅读更方便
你可能感兴趣的文章