Unity (U3D) 中如何修改 JSON 文件夹及 JSON 数据
在 Unity 开发中,JSON(JavaScript Object Notation)因其轻量级、易读易写的特性,常用于配置文件、数据存储、网络通信等场景,如何在 Unity 中修改 JSON 文件夹及 JSON 数据,是开发者必备的技能,本文将详细介绍 Unity 中修改 JSON 文件夹的方法、JSON 数据的读写操作,以及常见问题的解决方案。
Unity 中 JSON 文件夹的创建与管理
在 Unity 中,JSON 文件通常存储在项目的 Assets 目录下(如 Assets/Config、Assets/Data 等),以便于管理和引用,以下是创建和管理 JSON 文件夹的步骤:
创建 JSON 文件夹
- 在 Unity 编辑器的 Project 窗口中,右键点击 Assets 目录(或任意子目录)。
- 选择 Create → Folder,新建一个文件夹(例如命名为
Config或JsonData)。 - 若需将文件夹标记为“只读”或“只可读运行时”,可右键文件夹 → Import Settings,取消勾选
Write Enabled(但开发阶段通常保持可写,方便动态修改)。
放置 JSON 文件
将编辑好的 JSON 文件(如 config.json、playerData.json)直接拖拽到新建的文件夹中,Unity 会自动将其识别为 TextAsset(文本资源),默认导入方式为 TextScript(可直接读取为文本内容)。
修改 JSON 文件夹路径(可选)
若需调整 JSON 文件夹的存储位置(如移动到 Resources 目录或 StreamingAssets 目录),需注意不同目录的访问方式:
- StreamingAssets:用于存储运行时需要读取的原始文件(如配置、资源包),路径为
Application.streamingAssetsPath(Windows 为file://前缀,Android/iOS 为jar://或http://前缀)。 - Resources:通过
Resources.Load()加载的文件,路径需去掉Resources文件夹本身(如Config/config.json)。 - PersistentDataPath:用于运行时动态修改和存储的文件(如玩家存档),路径为
Application.persistentDataPath(可读写,但每次打包后路径会变化)。
Unity 中 JSON 数据的读取与修改
JSON 文件的核心是数据操作,Unity 中主要通过 JsonUtility(内置)或第三方库(如 Newtonsoft.Json、LitJson)实现 JSON 的序列化(对象转 JSON)和反序列化(JSON 转对象)。
使用 JsonUtility(推荐,Unity 5.3+ 内置)
JsonUtility 是 Unity 官方提供的 JSON 处理工具,支持与 C# 对象的双向转换,无需额外依赖。
(1)定义 C# 数据类
需创建与 JSON 结构匹配的 C# 类(或结构体),并使用 [Serializable] 特性标记(使其可被序列化),JSON 数据为:
{
"playerName": "Alice",
"level": 10,
"items": ["sword", "shield", "potion"]
}
对应的 C# 类为:
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class PlayerData
{
public string playerName;
public int level;
public List<string> items;
}
(2)读取 JSON 数据
若 JSON 文件位于 Assets/Config 目录下,可通过 TextAsset 读取并反序列化为对象:
using UnityEngine;
public class JsonReader : MonoBehaviour
{
public TextAsset jsonFile; // 在 Inspector 中拖拽 JSON 文件
void Start()
{
if (jsonFile != null)
{
PlayerData data = JsonUtility.FromJson<PlayerData>(jsonFile.text);
Debug.Log($"玩家名称: {data.playerName}, 等级: {data.level}");
Debug.Log($"物品列表: {string.Join(", ", data.items)}");
}
}
}
(3)修改 JSON 数据
若需动态修改 JSON 数据(如玩家升级、新增物品),步骤如下:
- 读取现有数据(同上)。
- 修改 C# 对象属性。
- 将对象重新序列化为 JSON 字符串。
- 保存字符串到文件(需写入
PersistentDataPath或StreamingAssets,注意权限)。
示例代码(运行时修改并保存):
using UnityEngine;
using System.IO;
using System.Text;
public class JsonModifier : MonoBehaviour
{
public TextAsset jsonFile; // 初始 JSON 文件(位于 Assets/Config)
private PlayerData playerData;
void Start()
{
// 1. 读取初始数据
playerData = JsonUtility.FromJson<PlayerData>(jsonFile.text);
Debug.Log($"初始数据: 等级 {playerData.level}");
// 2. 修改数据(玩家升级)
playerData.level += 1;
playerData.items.Add("newArmor");
// 3. 序列化为 JSON 字符串
string updatedJson = JsonUtility.ToJson(playerData, prettyPrint: true); // prettyPrint 格式化输出
// 4. 保存到 PersistentDataPath(可读写路径)
string savePath = Path.Combine(Application.persistentDataPath, "playerData.json");
File.WriteAllText(savePath, updatedJson);
Debug.Log($"数据已保存到: {savePath}");
Debug.Log($"更新后的 JSON:\n{updatedJson}");
}
}
使用第三方库(如 Newtonsoft.Json)
若需更灵活的 JSON 处理(如复杂类型、自定义格式),可引入 Newtonsoft.Json(需通过 NuGet 或 Unity Package Manager 安装)。
(1)安装 Newtonsoft.Json
- 打开 Unity,菜单栏 Window → Package Manager。
- 点击 “+” → Add package from git URL...,输入
com.unity.newtonsoft-json(或直接下载.tgz文件导入)。
(2)读取与修改 JSON
Newtonsoft.Json 的使用方式与 JsonUtility 类似,但支持更多特性(如 JsonIgnore、JsonProperty):
using UnityEngine;
using Newtonsoft.Json;
using System.IO;
public class NewtonsoftJsonExample : MonoBehaviour
{
public TextAsset jsonFile;
void Start()
{
// 反序列化
PlayerData data = JsonConvert.DeserializeObject<PlayerData>(jsonFile.text);
Debug.Log($"玩家: {data.playerName}");
// 修改数据
data.level = 15;
// 序列化(格式化)
string updatedJson = JsonConvert.SerializeObject(data, Formatting.Indented);
Debug.Log($"更新后的 JSON:\n{updatedJson}");
// 保存文件
File.WriteAllText(Path.Combine(Application.persistentDataPath, "playerData_newtonsoft.json"), updatedJson);
}
}
常见问题与解决方案
JSON 文件无法读取?检查路径与权限
-
路径问题:
StreamingAssets在 Android/iOS 上需特殊处理(不能直接用File.ReadAllText),需通过UnityWebRequest读取:using UnityEngine; using UnityEngine.Networking; using System.Collections; IEnumerator LoadStreamingAssetsJson(string fileName) { string path = Path.Combine(Application.streamingAssetsPath, fileName); using (UnityWebRequest request = UnityWebRequest.Get(path)) { yield return request.SendWebRequest(); if (request.result == UnityWebRequest.Result.Success) { PlayerData data = JsonUtility.FromJson<PlayerData>(request.downloadHandler.text); Debug.Log("加载成功: " + data.playerName); } else { Debug.LogError("加载失败: " + request.error); } } } -
权限问题:Android/iOS 上写入
PersistentDataPath需申请存储权限(通过PlayerSettings或插件处理)。
JsonUtility 不支持某些类型?改用第三方库
JsonUtility 限制较多(如不支持 Dictionary、List<List<T>> 等复杂类型),若需处理复杂数据,建议使用 Newtonsoft.Json 或 LitJson。Dictionary 的序列化需添加 [Serializable] 和自定义转换器:
// Newtonsoft.Json 示例
[Serializable]
public class PlayerData
{
[JsonProperty("itemDict")] // 自定义 JSON 属性名
public Dictionary<string, int> itemQuantities = new Dictionary<string, int>();
}
// 序列化时自动处理
string json = JsonConvert.SerializeObject(data);
修改 JSON 后文件未更新?检查保存逻辑
- 确保保存路径正确(如
PersistentDataPath而非Assets目录,运行时无法直接修改Assets下的文件)。 - 使用
File.WriteAllText时



还没有评论,来说两句吧...