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的文件夹下
解析方法的代码
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);
}
}
结果
注意事项
(1)用于接收的JSON实体类需要声明[Serializable] 序列化。
(2)使用Unity自带方法时,实体类如果是属性成员(public bool has_more{get;set;})的话,在序列化的时候会缺失这些成员,导致解析不出来。将属性改为字段即可。
(3)如何解析的对象是数组,自带的不能成功解析,可以人为将其封装为JSON对象。