一:介绍

JsonUtility是Unity自带的一个类,简单,效率高,不依赖第三方的库,但是对于一些复杂的要求还是需要导入第三方库去实现


二:使用

{
"personList":
[
{
"Name":"liu",
"Age":1
},
{
"Name":"Yin",
"Age":2
}
]
}
using System.Collections.Generic;
using UnityEngine;
using System;

public class ParseJson : MonoBehaviour
{
    private void Awake()
    {
        TextAsset json_txt = Resources.Load<TextAsset>("TestJson");
        PersonRoot data = JsonUtility.FromJson<PersonRoot>(json_txt.text);

        foreach (var temp in data.personList)
        {
            Debug.Log(String.Format("姓名:{0}==年龄{1}", temp.Name, temp.Age));
        }
    }
}

[Serializable]
public class PersonData
{
    public string Name;

    public int Age;
}

[Serializable]
public class PersonRoot
{
    public List<PersonData> personList;
}

三:踩坑点

——JsonUtility.FromJson方法只能接受一个JSON对象,否则会报错“JSON must represent an object type”
例如有多个对象时必须将多个对象定义为一个JSON对象

——无法直接解析枚举类型
JsonUtility无法直接解析枚举类型,需要在JSON文件中定义与枚举类型相对应的字符串类型,之后在实体类中实现ISerializationCallbackReceiver接口将字符串转换为枚举类型

using System.Collections.Generic;
using UnityEngine;
using System;

public class ParseJson : MonoBehaviour
{
    private void Awake()
    {
        TextAsset json_txt = Resources.Load<TextAsset>("TestJson");
        PersonRoot data = JsonUtility.FromJson<PersonRoot>(json_txt.text);

        foreach (var temp in data.personList)
        {
            Debug.Log(String.Format("姓名:{0}==年龄{1}==类型{2}", temp.Name, temp.Age, temp.PersonType));
        }
    }
}

[Serializable]
public class PersonData : ISerializationCallbackReceiver
{
    public string Name;

    public int Age;

    public PersonType PersonType;
    public string PersonTypeStr;

    public void OnAfterDeserialize()
    {
        PersonType type = (PersonType)Enum.Parse(typeof(PersonType), PersonTypeStr);
        PersonType = type;
    }

    public void OnBeforeSerialize()
    {
        throw new NotImplementedException();
    }
}

[Serializable]
public class PersonRoot
{
    public List<PersonData> personList;
}

public enum PersonType
{
    Teacher,
    Student,
}

GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:8 天前 )
960b763e 2 个月前
8c391e04 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐