解析json对象类的成员名要和json文件中键名一致,如果解析数组,必须对应类可序列化[System.Serializable]
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
[System.Serializable]
public class Person
{
public string name;
public int age;
}
[System.Serializable]
public class Persons
{
public List<Person> data;
public int num;
}
public class JsonLoad : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
string path = Application.dataPath + "/person.json";
StreamReader sr = new StreamReader(path);
if (sr != null) { }
else
Debug.Log("sr is null");
string json = sr.ReadToEnd();
Persons p = JsonUtility.FromJson<Persons>(json);
Debug.Log(p.num);
foreach(var o in p.data)
{
Debug.Log(o.name + o.age);
}
}
// Update is called once per frame
void Update()
{
}
}
对应json示例
{"data":[{"name":"li1","age":1},{"name":"li2","age":1},{"name":"li3","age":1}],"num":3}