JsonUtility 读取 Json

注意:

JsonUtility.FromJson 方法只能接受 json 对象,如果是 json 数组会提示错误 JSON must represent an object type

被转换的对象必须是可被序列化的,需要标记 [System.Serializable] 属性


模型类

[System.Serializable]
public class Item {

	public int id;
	public string name;
	public string sprite;

}

// 接受 api 返回的 json 数据
[System.Serializable]
public class ItemData {

	public List<Item> data;
	public int total;

}


Json 数据结构(必须是对象)

{
    "data": [
        {
            "id": 1,
            "name": "gun1",
            "sprite": "gun1.png"
        },
        {
            "id": 2,
            "name": "gun2",
            "sprite": "gun2.png"
        }
    ],
    "total": 2
}

测试:

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

public class DateTest : MonoBehaviour {

	void Start() {
		string jsonString = File.ReadAllText(Application.dataPath + "/Data/ItemJsonFromApi.json");
		ItemData itemDate = JsonUtility.FromJson<ItemData>(jsonString);
		Debug.Log(itemDate.total);
		foreach (var item in itemDate.data) {
			Debug.Log(item.name);
		}
	}

}

<think>首先,用户的问题是:“我想查找使用Unity的JsonUtility写入JSON数据的方法 请问Unity JsonUtility写入JSON数据的方法”。根据系统指令,我需要参考提供的站内引用,并生成相关问题。 提供的引用包括: - [^1]: 介绍了JsonUtility的基本用法和创建数据结构类。 - [^2]: 展示了如何使用JsonUtility写入JSON数据到一个文件中,包括创建文件、序列化对象列表和写入数据。 - [^3]: 讨论了保存JSON数据时的问题,如何创建文件路径和使用File操作。 - [^4]: 展示了JSON文件的结构示例。 用户的核心问题是关于Unity JsonUtility写入JSON数据的方法。所以,我需要基于这些引用,构建一个清晰的回答。 回答结构: 1. **介绍JsonUtility**:简要解释JsonUtility是什么,它在Unity中的用途。 2. **基本步骤**:列出使用JsonUtility写入JSON数据的关键步骤。 3. **示例代码**:提供基于引用的简单示例代码,确保使用正确格式。 4. **注意事项**:提到一些常见问题,如文件路径、序列化要求等。 5. **生成相关问题**:在末尾添加相关问题,符合指令要求。 关键点从引用中提取: - 从[^1],需要定义一个数据结构类(如StudentItem)。 - 从[^2],写入JSON的步骤如下: - 确保文件存在(使用File.Exists和File.CreateText)。 - 创建数据对象或列表。 - 使用JsonUtility.ToJson序列化对象。 - 使用StreamWriter写入文件到Application.dataPath。 - 关闭StreamWriter。 - 从[^3],需要注意文件路径(如Application.streamingAssetsPath),并确保序列化的类是可序列化的(添加[Serializable]属性)。 - JSON结构如[^4]所示。 回答中要使用中文,结构清晰,逐步解决问题。 生成相关问题: - 基于指令,在末尾添加相关问题。例如: 1. 如何处理JSON数据的读取? 2. JsonUtility序列化时的注意事项? 3. 如何在Unity中保存和加载复杂数据结构? 最后,确保所有数学表达式使用$...$或$$...$$格式,但在这个上下文中可能不涉及数学,所以可能不需要。但如果有,要正确处理。 回答大纲: - 开头:直接回答方法。 - 步骤: - 步骤1: 定义数据结构类(使用[Serializable])。 - 步骤2: 创建或确保JSON文件存在。 - 步骤3: 填充数据。 - 步骤4: 序列化数据。 - 步骤5: 写入文件。 - 步骤6: 关闭文件流。 - 代码示例:给出一个简化的代码示例。 - 结尾注意事项:如路径问题、序列化限制。 - 相关问题:添加3-5个相关问题。 </think>### Unity JsonUtility写入JSON数据的方法 在Unity中,使用`JsonUtility`类可以高效地将C#对象序列化为JSON格式并写入文件。这常用于保存游戏数据、配置信息等。以下是基于参考内容的完整方法步骤,确保操作可靠且符合Unity的最佳实践[^1][^2]。 #### 步骤详解 1. **定义可序列化的数据结构类** 创建一个C#类,并标记为`[Serializable]`,确保字段能被`JsonUtility`识别。例如: ```csharp [System.Serializable] public class StudentItem { public int id; public string name; public float score; // 构造函数可选 public StudentItem(int id, string name, float score) { this.id = id; this.name = name; this.score = score; } } ``` - **关键点**: 类必须使用`[Serializable]`属性,否则序列化失败。字段必须是public或标记为`[SerializeField]`[^1][^3]。 2. **确保目标文件存在并准备写入路径** 使用Unity的路径API(如`Application.dataPath`或`Application.streamingAssetsPath`)生成文件路径,并检查文件是否存在: ```csharp string filePath = Application.dataPath + "/StudentData.json"; // 示例路径 if (!File.Exists(filePath)) { File.CreateText(filePath).Dispose(); // 创建文件并释放资源 } ``` - **注意**: 使用`File.CreateText`后必须调用`.Dispose()`或`Close()`,避免文件锁定问题[^2][^3]。推荐`Application.streamingAssetsPath`用于只读数据,`Application.persistentDataPath`用于可读写数据[^3]。 3. **填充数据并序列化为JSON字符串** 实例化对象或列表,使用`JsonUtility.ToJson`进行序列化: ```csharp List<StudentItem> studentList = new List<StudentItem>(); studentList.Add(new StudentItem(10001, "张三", 80f)); studentList.Add(new StudentItem(10002, "李四", 60f)); // 序列化单一对象或列表 string jsonData = JsonUtility.ToJson(studentList); // 直接序列化列表 // 或自定义JSON结构(如添加根节点) // string jsonData = "{\"students\": " + JsonUtility.ToJson(studentList) + "}"; ``` - **优化**: 对于列表对象,可以直接序列化整个列表。复杂的嵌套结构需确保所有子类均可序列化[^2][^4]。 4. **写入文件并关闭流** 使用`StreamWriter`或`File.WriteAllText`将JSON数据写入文件: ```csharp using (StreamWriter sw = new StreamWriter(filePath)) { sw.Write(jsonData); // 写入数据 } // using块自动关闭流,避免资源泄漏 ``` - **最佳实践**: 始终使用`using`语句或手动`Close()`流,防止文件访问错误。写入后可选调试日志验证(如`Debug.Log("保存成功");`)[^2][^3]。 #### 完整示例代码 以下脚本演示了整个写入流程(保存为`JsonWriter.cs`并挂载到Unity GameObject): ```csharp using System.Collections.Generic; using UnityEngine; using System.IO; using System; [Serializable] public class StudentItem { public int id; public string name; public float score; public StudentItem(int id, string name, float score) { this.id = id; this.name = name; this.score = score; } } public class JsonWriter : MonoBehaviour { void Start() { string filePath = Application.dataPath + "/StudentData.json"; // 创建文件(如果不存在) if (!File.Exists(filePath)) { File.Create(filePath).Dispose(); } // 填充数据 List<StudentItem> students = new List<StudentItem>(); students.Add(new StudentItem(10001, "张三", 80f)); students.Add(new StudentItem(10002, "李四", 60f)); // 序列化列表 string jsonData = JsonUtility.ToJson(students, true); // true参数美化JSON格式 // 写入文件 File.WriteAllText(filePath, jsonData); Debug.Log("JSON数据写入成功!"); } } ``` - **输出JSON文件示例**(位于`Assets/StudentData.json`): ```json [ { "id": 10001, "name": "张三", "score": 80.0 }, { "id": 10002, "name": "李四", "score": 60.0 } ] ``` #### 注意事项 - **序列化限制**: `JsonUtility`不支持序列化字典或复杂嵌套类型(如`List<List<T>>`),需转为简单结构[^2][^4]。 - **路径问题**: 在编辑器模式下使用`Application.dataPath`,但发布后推荐`Application.persistentDataPath`以确保跨平台兼容性[^3]。 - **错误处理**: 添加`try-catch`块捕获IO异常(如文件权限错误),确保数据完整性[^3]。 通过以上方法,您能可靠地在Unity中写入JSON数据。如需读取JSON,可使用`JsonUtility.FromJson`方法[^4]。
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值