一、服务器中json信息格式
错误格式:
[{“url”:“adr1”},{“url”:“adr2”},{“url”:“adr3”}]
正确格式:
{ “picInfoArray”:[{“url”:“adr1”},{“url”:“adr2”},{“url”:“adr3”}] }
我本来只想要[{“url”:“adr1”},{“url”:“adr2”},{“url”:“adr3”}],但是格式不对。必须还得在外面套个壳。
二、接收内容页代码
//引用
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
//存储从服务器接收到的文件
public string receive;
//接收数据方法
IEnumerator PostMsg(string methodName, string jsonParas)
{
string PostUrl = "这里填写服务器的URL";//服务器url
// 创建UnityWebRequest对象,指定URL和请求方法为GET
UnityWebRequest request = new UnityWebRequest(PostUrl,"GET");
request.downloadHandler = new DownloadHandlerBuffer();
//设置请求的头部信息 ,这里意思是json信息
request.SetRequestHeader("Content-Type","application/json");
// 设置跨域请求所需的头部信息
request.SetRequestHeader("Access-Control-Allow-Origin", "*");
request.SetRequestHeader("Access-Control-Allow-Method", "*");
request.SetRequestHeader("Access-Control-Allow-Headers", "*");
//发送请求
yield return request.SendWebRequest();
//检查是否有错误发生
if (request.isDone && !request.isNetworkError)
{
//请求成功,处理相应数据
receive = request.downloadHandler.text;
//cailiao是我定义的跟json整体内容格式相同的List
caiLiaoAtt = JsonUtility.FromJson<cailiao>(str);
//我的json数据是以data包的壳,所以得先.data
//比如:caiLiaoAtt.data[0].image
}
else
{
Debug.Log(request.error);
}
yield return "success";
}
三、结构
//总结构
[System.Serializable]
public class cailiao
{
public List<CaiLiaoAtt> data = new List<CaiLiaoAtt>();
}
//需要使用到的内容
[System.Serializable]
public class CaiLiaoAtt
{
public string id;
public string category;//类别
public string name;
public string image;
public string description;//语音
public string detail;//介绍
public string price;
}
注意,接收的结构上面要加上可序列化