怎么在unity3D工程中导入Newtonsoft.Json
unity旧版本自带的json接口太难用了(JsonUtility),不能序列化字典和列表等对象,只能序列化基础类型对象,所以基本等于没有。
在git上下载Newtonsoft.Json-for-Unity-master的压缩文件(.zip),解压之后,复制到unity3D工程的Asset/Plugins文件夹下就可以用了,
在脚本中就可以使用Newtonsoft.Json了,例如下述代码:
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using System.IO;
public class Player : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
string json = JsonConvert.SerializeObject(
new Dictionary<string, string> {
{ "123", "123" },{ "456", "456" }, });
string path = Application.persistentDataPath + "/saveFile.json";
File.WriteAllText(path, json);
}
// Update is called once per frame
void Update()
{
}
}
经过验证,上述方法不行(具体原因后续查),可以采用如下方式安装json包
-
打开 Unity 编辑器。
-
转到菜单栏的 “Window”(窗口)选项,然后选择 “Package Manager”(包管理器)。
-
在 Package Manager 窗口中,选择 “All”(全部)选项卡。
-
在搜索框中输入 “Json.NET” 或 “Newtonsoft.Json” 进行搜索。
-
在搜索结果中,应该会看到 “Json.NET for Unity” 或类似名称的项目。
-
单击搜索结果下方的 “Install”(安装)按钮。
-
等待 Unity 下载并安装 Newtonsoft.Json 包。
在2022.3.2f1c1中亲测可以