Unity请求URL,json解析数据
程序员文章站
2024-01-20 13:44:34
...
后台接口,输入课程id 请求下面的url ,获取json信息
远程请求URL获取的json内容格式,先贴出来
{
"code": "200",
"data": {
"CourseNoticeList": [
{
"id": "1",
"Title": "asdf",
"Content": "fasdfasdfasdfasdf"
},
{
"id": "2",
"Title": "aaaaaa",
"Content": "hhhhhaaaaa"
},
{
"id": "4",
"Title": "1",
"Content": "1"
},
{
"id": "6",
"Title": "1",
"Content": "21"
},
{
"id": "11",
"Title": "11111111",
"Content": "11111"
}
]
},
"msg": "操作成功",
"success": true
}
加入LitJson.dll
根据json内容,创建courseStuNoticeData类,包含json里的详细内容
using System;
using System.Collections;
using System.Collections.Generic;
using LitJson;
using UnityEngine;
public class courseStuNoticeData
{
public string id;
public string Content;
public string Title;
public static List<courseStuNoticeData> DesJsonList(string json)
{
List<courseStuNoticeData> resourceDatas = new List<courseStuNoticeData>();
JsonData data = JsonMapper.ToObject<JsonData>(json);
foreach (JsonData jsonData in data)
{
courseStuNoticeData rd = DesJsonData(jsonData.ToJson());
resourceDatas.Add(rd);
}
return resourceDatas;
}
public static courseStuNoticeData DesJsonData(string json)
{
//JsonObject jsonData = SimpleJson.SimpleJson.DeserializeObject<JsonObject>(json);
JsonData jsonData = JsonMapper.ToObject<JsonData>(json);
courseStuNoticeData rd = new courseStuNoticeData();
//rd.id = Convert.ToString(jsonData["id"].ToString());
if (jsonData["id"] != null)
{
rd.id = Convert.ToString(jsonData["id"].ToString());
}
if (jsonData["Content"] != null)
{
rd.Content = Convert.ToString(jsonData["Content"].ToString());
}
if (jsonData["Title"] != null)
{
rd.Title = Convert.ToString(jsonData["Title"].ToString());
}
return rd;
}
}
(请求URL的方法post,get),下面调用post
//GetUrl方法
public Coroutine GetUrl(string url, Action<float> processAction = null, Action<DownloadHandler> doneAction = null,
Action<string> errorAction = null, int tryTime = 2, int timeout = 3)
{
return StartCoroutine(GetUrlCor(url, processAction, doneAction, errorAction, tryTime, timeout));
}
private IEnumerator GetUrlCor(string url, Action<float> processAction = null,
Action<DownloadHandler> doneAction = null,
Action<string> errorAction = null, int tryTime = 2, int timeout = 3)
{
tryTime--;
UnityWebRequest unityWebRequest = UnityWebRequest.Get(url);
unityWebRequest.timeout = timeout;
var oper = unityWebRequest.SendWebRequest();
if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError)
{
if (errorAction != null)
{
if (tryTime == 0)
{
Debug.LogError(unityWebRequest.error);
errorAction(unityWebRequest.error);
}
else
{
GetUrl(url, processAction, doneAction, errorAction, tryTime, timeout);
}
}
}
else
{
while (!oper.isDone)
{
yield return null;
if (processAction != null)
{
processAction(oper.progress);
}
if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError)
{
if (errorAction != null)
{
if (tryTime == 0)
{
Debug.LogError(unityWebRequest.error);
errorAction(unityWebRequest.error);
break;
}
else
{
GetUrl(url, processAction, doneAction, errorAction, tryTime, timeout);
break;
}
}
}
}
if (doneAction != null)
{
if (!(unityWebRequest.isNetworkError || unityWebRequest.isHttpError))
{
processAction?.Invoke(1);
doneAction?.Invoke(unityWebRequest.downloadHandler);
}
else
{
if (errorAction != null)
{
if (tryTime == 0)
{
Debug.LogError(unityWebRequest.error);
errorAction(unityWebRequest.error);
}
else
{
GetUrl(url, processAction, doneAction, errorAction, tryTime, timeout);
}
}
}
}
}
}
//PostUrl方法
public Coroutine PostUrl(string url, WWWForm form, Action<float> processAction = null,
Action<DownloadHandler> doneAction = null,
Action<string> errorAction = null, int tryTime = 2, int timeout = 3)
{
return StartCoroutine(PostUrlCor(url, form, processAction, doneAction, errorAction, tryTime, timeout));
}
private IEnumerator PostUrlCor(string url, WWWForm form, Action<float> processAction = null,
Action<DownloadHandler> doneAction = null,
Action<string> errorAction = null, int tryTime = 2, int timeout = 3)
{
tryTime--;
UnityWebRequest unityWebRequest = UnityWebRequest.Post(url, form);
unityWebRequest.timeout = timeout;
UnityWebRequestAsyncOperation oper = unityWebRequest.SendWebRequest();
if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError)
{
if (errorAction != null)
{
if (tryTime == 0)
{
Debug.LogError(unityWebRequest.error);
errorAction(unityWebRequest.error);
}
else
{
PostUrl(url, form, processAction, doneAction, errorAction, tryTime, timeout);
}
}
}
else
{
while (!oper.isDone)
{
yield return null;
if (processAction != null)
{
processAction(oper.progress);
}
if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError)
{
if (errorAction != null)
{
if (tryTime == 0)
{
// Debug.LogError(unityWebRequest.error);
errorAction(unityWebRequest.error);
break;
}
else
{
PostUrl(url, form, processAction, doneAction, errorAction, tryTime, timeout);
break;
}
}
}
}
if (doneAction != null)
{
if (!(unityWebRequest.isNetworkError || unityWebRequest.isHttpError))
{
processAction?.Invoke(1);
doneAction?.Invoke(unityWebRequest.downloadHandler);
}
else
{
if (errorAction != null)
{
if (tryTime == 0)
{
//Debug.LogError(unityWebRequest.error);
errorAction(unityWebRequest.error);
}
else
{
PostUrl(url, form, processAction, doneAction, errorAction, tryTime, timeout);
}
}
}
}
}
}
请求URL获取json信息, 给Data类的属性进行赋值
//学生课程通知消息列表
//(url前缀:http://116.255.142.113:8997/LTJCApi/courseStuNoticeList?,输入的参数id:courseid=1,请求时加载loading ,委托)
public void GetcourseStuNoticeData(string url, string courseid, GameObject loading,
Action<List<courseStuNoticeData>> cb)
{
loading.SetActive(true);
WWWForm form = new WWWForm();
form.AddField("courseid", courseid);
PostUrl(url, form, null, (handler) =>
{
loading.SetActive(false);
string str = handler.text;
Debug.Log("over" + str);
JsonData data = JsonMapper.ToObject<JsonData>(str);
int code = Convert.ToInt32(data["code"].ToString());
if (code == 200)
{
string data1 = data["data"]["CourseNoticeList"].ToJson();
if (data1 != "")
{
Debug.Log(data1);
List<courseStuNoticeData> messdatas = courseStuNoticeData.DesJsonList(data1); //到数据解析方法
cb?.Invoke(messdatas);
}
else
{
//TTUIPage.ShowPage<TipUI>("消息列表为空");
}
}
else
{
cb(null);
}
}, (e) => { //请求服务器有误TTUIPage.ShowPage<TipUI>("获取学生课程通知消息列表连接服务器失败"); }, 2, 3);
}
数据获取到后UI曾调用,获取详细信息
GetcourseStuNoticeData("http://116.255.142.113:8997/LTJCApi/courseStuNoticeList?", courseid, loading,
(b) => // b=List<SearchKeywordsData>
{
//获取到信息后的操作逻辑
msgList = b;
foreach (courseStuNoticeData data in b)
{
Debug.Log(data.Title);//获取Title
Debug.Log(data.id);//获取id
}
if (b.Count == 0)
{
Debug.Log("没有搜索到相关内容");
}
});
---------------------------------------------------------------------
下面是嵌套多个list类型的json解析
创建SaoMiaoHistoryData类,包含三个类scanYesData类,sanYiZhouData类,scanTodayData类,每个类再写一个class类
using System;
using System.Collections;
using System.Collections.Generic;
using LitJson;
using SimpleJson;
using UnityEngine;
//扫描历史类,包括今天类,昨天类,上一周类
public class SaoMiaoHistoryData
{
public List<scanYesData> ScanYesDatasList;
public List<sanYiZhouData> ScaYiZhouDatasList;
public List<scanTodayData> ScanTodayDatasList;
public static SaoMiaoHistoryData DesJsonData( string json)
{
SaoMiaoHistoryData saomiaodata=new SaoMiaoHistoryData();
JsonData jsonData = JsonMapper.ToObject(json);
saomiaodata.ScanYesDatasList = JsonMapper.ToObject<List<scanYesData>>(jsonData["scanYesList"].ToJson());
saomiaodata.ScaYiZhouDatasList = JsonMapper.ToObject<List<sanYiZhouData>>(jsonData["sanYiZhouList"].ToJson());
saomiaodata.ScanTodayDatasList = JsonMapper.ToObject<List<scanTodayData>>(jsonData["scanTodayList"].ToJson());
//Debug.Log(saomiaodata.ScanTodayDatasList.Count);
//Debug.Log(saomiaodata.ScaYiZhouDatasList.Count);
//Debug.Log(saomiaodata.ScanTodayDatasList.Count);
return saomiaodata;
}
}
//昨天类
public class scanYesData
{
public string id;
public string Resourceid;
public string Inserttime;
public string Userid;
public string Resourcename;
public static scanYesData DesJsonData(string json)
{
scanYesData scanYesData = new scanYesData();
JsonData jsonData = JsonMapper.ToObject(json);
if (jsonData["id"]!=null)
{
scanYesData.id = Convert.ToString(jsonData["id"]);
}
if (jsonData["Resourceid"] != null)
{
scanYesData.Resourceid = Convert.ToString(jsonData["Resourceid"]);
}
if (jsonData["Inserttime"] != null)
{
scanYesData.Inserttime = Convert.ToString(jsonData["Inserttime"]);
}
if (jsonData["Userid"] != null)
{
scanYesData.Userid = Convert.ToString(jsonData["Userid"]);
}
if (jsonData["Resourcename"] != null)
{
scanYesData.Resourcename = Convert.ToString(jsonData["Resourcename"]);
}
return scanYesData;
}
public static List<scanYesData> DesJsonList(string json)
{
List<scanYesData> resourceDatas = new List<scanYesData>();
JsonData data = JsonMapper.ToObject(json);
Debug.Log(data);
foreach (JsonObject jsonData in data)
{
scanYesData rd = DesJsonData(jsonData.ToString());
resourceDatas.Add(rd);
}
return resourceDatas;
}
}
//上一周类
public class sanYiZhouData
{
public string id;
public string Resourceid;
public string Inserttime;
public string Userid;
public string Resourcename;
public static sanYiZhouData DesJsonData(string json)
{
sanYiZhouData sanYiZhouData = new sanYiZhouData();
JsonData jsonData = JsonMapper.ToObject(json);
sanYiZhouData.id = Convert.ToString(jsonData["id"]);
sanYiZhouData.Resourceid = Convert.ToString(jsonData["Resourceid"]);
sanYiZhouData.Inserttime = Convert.ToString(jsonData["Inserttime"]);
sanYiZhouData.Userid = Convert.ToString(jsonData["Userid"]);
sanYiZhouData.Resourcename = Convert.ToString(jsonData["Resourcename"]);
return sanYiZhouData;
}
public static List<sanYiZhouData> DesJsonList(string json)
{
List<sanYiZhouData> resourceDatas = new List<sanYiZhouData>();
JsonData data = JsonMapper.ToObject(json);
Debug.Log(data);
foreach (JsonObject jsonData in data)
{
sanYiZhouData rd = DesJsonData(jsonData.ToString());
resourceDatas.Add(rd);
}
return resourceDatas;
}
}
//今天类
public class scanTodayData
{
public string id;
public string Resourceid;
public string Inserttime;
public string Userid;
public string Resourcename;
public static scanTodayData DesJsonData(string json)
{
scanTodayData scanTodayData = new scanTodayData();
JsonData jsonData = JsonMapper.ToObject(json);
scanTodayData.id = Convert.ToString(jsonData["id"]);
scanTodayData.Resourceid = Convert.ToString(jsonData["Resourceid"]);
scanTodayData.Inserttime = Convert.ToString(jsonData["Inserttime"]);
scanTodayData.Userid = Convert.ToString(jsonData["Userid"]);
scanTodayData.Resourcename = Convert.ToString(jsonData["Resourcename"]);
return scanTodayData;
}
public static List<scanTodayData> DesJsonList(string json)
{
List<scanTodayData> resourceDatas = new List<scanTodayData>();
JsonData data = JsonMapper.ToObject(json);
Debug.Log(data);
foreach (JsonObject jsonData in data)
{
scanTodayData rd = DesJsonData(jsonData.ToString());
resourceDatas.Add(rd);
}
return resourceDatas;
}
}
//扫描历史记录,初始化SaoMiaoHistoryData类数据,赋值
public void GetSaoMiaoHistoryData(string url, string userid, GameObject loading, Action<SaoMiaoHistoryData> cb)
{
loading.SetActive(true);
WWWForm form = new WWWForm();
form.AddField("userid", userid);
Util.instance.PostUrl(url, form, null, (handler) =>
{
loading.SetActive(false);
string str = handler.text;
Debug.Log(str);
JsonObject jsonObject = SimpleJson.SimpleJson.DeserializeObject<JsonObject>(str);
if (Convert.ToInt32(jsonObject["code"]) == 200)
{
string data = Convert.ToString(jsonObject["data"]);
if (data != "")
{
//JsonData da = JsonMapper.ToObject(data);
//Debug.Log(da["scanYesList"].Count);
//Debug.Log(da["scanYesList"].ToJson());
//Debug.Log(da["scanYesList"][1]["Inserttime"]);
SaoMiaoHistoryData SM = SaoMiaoHistoryData.DesJsonData(data);
cb?.Invoke(SM);
}
else
{
TTUIPage.ShowPage<TipUI>("扫描历史记录为空");
}
}
else
{
TTUIPage.ShowPage<TipUI>("扫描历史列表为空");
cb(null);
}
}, (e) => { }, 2, 3);
}
UI层调用获取数据
private List<scanYesData> scanYesDatas;
private List<scanTodayData> scanTodayDatas;
private List<sanYiZhouData> sanYiZhouDatas;
public override void Refresh()
{
DestroyChildrens(zuixinContent);
GetSaoMiaoHistoryData(GM.apiUrl + "zhuReshistoryList", PlayerPrefs.GetString("userId"), loading,
(b) =>
{
scanTodayDatas = b.ScanTodayDatasList;
scanYesDatas = b.ScanYesDatasList;
sanYiZhouDatas = b.ScaYiZhouDatasList;
//for (int i = 0; i < scanTodayDatas.Count; i++)
//{
// CreateAndShowToday( zuixinContent, scanTodayDatas[i], SaomiaoItem);
//}
//todayButtonClick();
});
}
上一篇: Liunx如何安装nginx
下一篇: 设计模式的简单工厂模式实例