Unity解析JSON的几种方式
1.使用JsonUtility(Unity自带)解析数据
踩坑
*用于接收的JSON实体类需要声明[Serializable] 序列化。
*使用Unity自带方法时,实体类如果是属性成员(public string mname{get;set;})的话,
*在序列化的时候会缺失这些成员,导致解析不出来。将属性改为字段即(public string mname;)。
var uri = new System.Uri(Path.Combine(Application.streamingAssetsPath, "demoText.json"));
UnityWebRequest request = UnityWebRequest.Get(uri);
yield return request.SendWebRequest();
if (request.isNetworkError)
{
Debug.Log(request.error);
}
else
{
string jsonStr = request.downloadHandler.text;
RootDate Data= JsonUtility.FromJson<RootDate >(jsonStr);
}
2.使用Newtonsoft.Json dll解析json 链接: link
var uri = new System.Uri(Path.Combine(Application.streamingAssetsPath, "demoText.json"));
UnityWebRequest request = UnityWebRequest.Get(uri);
yield return request.SendWebRequest();
if (request.isNetworkError)
{
Debug.Log(request.error);
}
else
{
string jsonStr = request.downloadHandler.text;
RootDate Data = JsonConvert.DeserializeObject<RootDate >(jsonStr);
}
3.使用LitJson解析数据文章来源:https://www.toymoban.com/news/detail-601671.html
var uri = new System.Uri(Path.Combine(Application.streamingAssetsPath, "demoText.json"));
UnityWebRequest request = UnityWebRequest.Get(uri);
yield return request.SendWebRequest();
if (request.isNetworkError)
{
Debug.Log(request.error);
}
else
{
string jsonStr = request.downloadHandler.text;
RootDate Data= JsonMapper.ToObject<RootDate>(jsonStr);
}
4.传递给前端或后端 json文章来源地址https://www.toymoban.com/news/detail-601671.html
1.一种直接使用jsonData
JsonData data = new JsonData();
data["pageSize"] = "sd";
data["currentPage"] = "s";
data["startTime"] = "sdsdsd";
data["endTime"] = "sdsadsdsadsad";
var da = JsonMapper.ToJson(data);
2.另一种自写一个类
Testdate testdate = new Testdate();
testdate.name = "sdsad";
testdate.code = 1;
var da = JsonMapper.ToJson(testdate);
到了这里,关于Unity解析JSON的几种方式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!