本文主要是介绍jsonUtility读取json文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
解析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 updatevoid Start(){string path = Application.dataPath + "/person.json";StreamReader sr = new StreamReader(path);if (sr != null) { }elseDebug.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 framevoid Update(){}
}
对应json示例
{"data":[{"name":"li1","age":1},{"name":"li2","age":1},{"name":"li3","age":1}],"num":3}
这篇关于jsonUtility读取json文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!