Unity数据持久化设计二 JSON

Unity数据持久化设计

第一章: Unity数据持久化设计一 PlayerPrefs



引言

之前整理了Unity数据持久化方法之一的PlayerPrefs存储的只是内容,也对其进行了封装优化使用,但是该方法有一定的缺陷,且不适用于大项目的设计开发。


1. JSON序列化基础概念

1.1 什么是JSON

JSON是JavaScript Object Notation的简称,是一种轻量级的数据交换格式,主要是运用再网络通信数据传输中或者是本地数据存储和读取的操作。
JSON易于阅读和编写,同时也易于机器解析和生成,并能够有效的提高网络传输效率。

1.2 Unity中的JSON解决方案

Unity提供了JsonUnitily作为内置的JSON序列化工具,也可以选择第三方库LitJson来实现更复杂的功能需求。两种使用各有优势:
JsonUnitily:Unity内置,适配性更高一些,于Unity序列化系统有良好的集成。
LitJson:功能强大,支持更多数据类型存储(如字典),单需要单独导入配置。

2. Unity内置的JsonUnitily

2.1 基本使用方法

JsonUnitily的核心功能是将对象于JSON格式之间进行互相转换,要使用JsonUnitily就必须让其具备序列化属性[System.Serializable]
基础的序列化使用示例:

[System.Serializable]
public class PlayerData
{
   
   
    public string playerName;
    public int level;
    public float experience;
    public int health;
    public bool isPremium;
}

public class JsonExample : MonoBehaviour
{
   
   
    void Start()
    {
   
   
        // 创建玩家数据对象
        PlayerData player = new PlayerData();
        player.playerName = "冒险者";
        player.level = 15;
        player.experience = 1250.5f;
        player.health = 85;
        player.isPremium = true;
        
        // 序列化为JSON字符串
        string json = JsonUtility.ToJson(player);
        Debug.Log("序列化结果: " + json);
        // 输出: {"playerName":"冒险者","level":15,"experience":1250.5,"health":85,"isPremium":true}
        
        // 反序列化
        PlayerData loadedPlayer = JsonUtility.FromJson<PlayerData>(json);
        Debug.Log($"加载玩家: {
     
     loadedPlayer.playerName}, 等级: {
     
     loadedPlayer.level}");
    }
}

想要实现Json存储需要再文件中存读字符串,这个时候就需要使用相应的存储路径来实现文件操作。

  • 序列化方法
    将内存中的数据存储到硬盘上,将对象转换成为Json字符串数据,使用的方法为JsonUnitily.ToJson(),参数是带转换的对象。
    示例:
	Player obj =new Player();
	obj.name="小明";
	obj.tag="Player";
	string 
	jsonStr=JsonUnitily.ToJson(obj);
	File.WriteAllText(Application.persistentDataPath+"/JsonTest.json",jsonStr);

在使用过程中需要注意一些问题,如序列化浮点型数据的时候看起来会有一些误差,自定义类需要加上序列化特性,如果想要序列化私有变量的时候也需要加上序列化特性,只是与前者有区别,使用的是[SerializeField]。

  • 反序列化方法

2.2 JsonUnitily的灵活用法

可以使用FromJsonOverwrite更新现有对象,例如:

public class PlayerState : MonoBehaviour
{
   
   
    public string playerName;
    public int lives;
    public float health;
    
    public void Load(string savedData)
    {
   
   
        // 使用FromJsonOverwrite更新当前对象,而不是创建新实例
        JsonUtility.FromJsonOverwrite(savedData, this);
    }
    
    void Example()
    {
   
   
        // 假设JSON数据: {"lives":3, "health":0.8}
        string jsonData = "{\"lives\":3, \"health\":0.8}";
        Load(jsonData);
        // lives现在是3,health是0.8,playerName保持不变:cite[4]
    }
}

需要注意的是与FromJson创建新对象不同mFromJsonOverwrite会将JSON数据加载到现有对象中,相当于更新其字段信息,这在需要重复使用的对象以最小化分配,或者仅用部分JSON数据进行修补对象时就很灵活很有用。

2.3 JsonUnitily的局限性

JsonUnitily虽然方便,但依然有一定的限制,例如:
1)不支持字典类型存储
2)之序列化公有对象
3)不支持复杂继承结构
4)不能直接序列化基础类型和数组

3. LitJson第三方库使用

3.1 LitJson的导入与配置

LitJson是一个.NET库,主要用于处理JSON字符串之间的转换。

  • 导入步骤
    下载LitJson.dll文件,下载地址:
    将下载的dll文件导入到项目资源区Assets
    在使用脚本中引入using LitJson命名空间进行代码API引用。

3.2 LitJson基础用法

LitJson实现对数据的序列化与反序列化需要通过LitJson内置的JsonMapper进行引用获取实现,其中对序列化使用的是ToJson使用,反序列化使用的是ToObject实现。

  • 序列化:ToJson
    相对于JsonUnitily来说,LitJson不需要加特性,当然也是不能序列化私有变量,但是在字典类型的支持转换上还有允许的,这也是JsonUnitily与LitJson之间的区别。
    LitJson存储的时候可以准确的保存Null类型,序列化的示例如下:
	using LitJson;
using System.Collections.Generic;

[System.Serializable]
public class Person
{
   
   
    public int age;
    public int[] id = {
   
    1, 2, 3 };
    public Dictionary<string, int> dic = new Dictionary<string, int>();
    public List<string> skills;
}

public class LitJsonExample : MonoBehaviour
{
   
   
    void Start()
    {
   
   
        Person person = new Person();
        person.age = 25;
        person.dic.Add("战斗力", 95);
        person.dic.Add("防御力", 80);
        person.skills = new List<string> {
   
    "剑术", "魔法", "治疗" };
        
        // 序列化 - 注意LitJson支持字典类型:cite[8]
        string json = JsonMapper.ToJson(person);
        Debug.Log("LitJson序列化结果: " + json);
        
        // 将JSON数据保存到文件
        string filePath = System.IO.Path.Combine(Application.persistentDataPath, "playerData.json");
        System.IO.File.WriteAllText(filePath, json);
        Debug.Log($"JSON数据已保存至: {
     
     filePath}");       
    }
}
	
  • 反序列化:ToObject
	using LitJson;
using System.Collections.Generic;

[System.Serializable]
public class Person
{
   
   
    public int age;
    public int[] id = {
   
    1, 2, 3 };
    public Dictionary<string, int> dic = new Dictionary<string, int>();
    public List<string> skills;
}

public class LitJsonExample : MonoBehaviour
{
   
   
    void Start()
    {
   
   
        Person person = new Person();
        person.age = 25;
        person.dic.Add("战斗力", 95)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值