Json实体类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class StudentData
{
public string StudentName;
public string StudentGender;
public string StudentAge;
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace Assets.UIFrameWork
{
[System.Serializable]
public class StudentDataItems
{
public StudentData[] infoList;
}
}
Json
{
"infoList": [
{
"StudentName": "张三",
"StudentGender": "男",
"StudentAge": "23"
},
{
"StudentName": "李四",
"StudentGender": "女",
"StudentAge": "23"
},
{
"StudentName": "王五",
"StudentGender": "男",
"StudentAge": "23"
}
]
}
把Json文件放到名字为Resources的文件夹下 ![在这里插入图片描述](https://img-blog.csdnimg.cn/61da539cae214c7bac5206a6d8882f82.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5pu-6IOW56We54i2,size_20,color_FFFFFF,t_70,g_se,x_16)
解析方法的代码
public void ParseJsonToStr()
{
TextAsset ta = Resources.Load<TextAsset>("uiJson");
byte[] ReadByte = Encoding.UTF8.GetBytes(ta.text);
StudentDataItems dataItems = JsonUtility.FromJson<StudentDataItems>(UTF8Encoding.UTF8.GetString(ReadByte));
foreach(StudentData studentData in dataItems.infoList)
{
Debug.Log("学生姓名为"+studentData.StudentName);
}
}
结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/25b4ba512c6c46cc93127700b74a8a81.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5pu-6IOW56We54i2,size_20,color_FFFFFF,t_70,g_se,x_16)
注意事项
(1)用于接收的JSON实体类需要声明[Serializable] 序列化。 (2)使用Unity自带方法时,实体类如果是属性成员(public bool has_more{get;set;})的话,在序列化的时候会缺失这些成员,导致解析不出来。将属性改为字段即可。 (3)如何解析的对象是数组,自带的不能成功解析,可以人为将其封装为JSON对象。
|