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 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}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值