unity c# 读写 json 数组(FromJson / ToJson)

本文介绍了如何在Unity3D中使用JsonUtility进行Json的写入和读取操作。对于写入,需先将数据转换为对象数组,然后通过ToJson方法生成Json字符串。读取时,根据Json格式选择合适的对象类型,使用FromJson方法解析Json文本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Json 的写入 (ToJson)

写入的一定是一个完整的 object,不能是 object 的数组

ref tojson

定义对象为

[Serializable]
public class UserObject
{
    public int userId;
    public int id;
    public string title;
    public string body;
}

// !!! 注意:需要在自己定义的对象基础上,再定义一个数组对象
[Serializable]
public class RootObject
{
    public UserObject[] users;
}
List<UserObject> UserObjectList = new List<UserObject>();

for (int i = 0; i < 10; i++) {
	UserObject json = new UserObject();
	json.userId = i;
	json.id = i;
	json.title = "title"";
	json.body = "---";
	UserObjectList.Add(json);
}


string JsonPath = Application.dataPath + "/out.json";  
if (!File.Exists(JsonPath))  
{  
    File.Create(JsonPath);  
}  

 //!!!关键代码
 // 把 List 转化为 Array 后创建一个 RootObject 实例,将它导出为 json
string result = JsonUtility.ToJson(new RootObject(UserObjectList.ToArray())); 

File.WriteAllText(JsonPath , result);

Json 的读取 (FromJson)

读取的时候一定要是一个完整的 object

ref json must represent an object type

如果 text 的格式为一个json对象:

{
    "userId": 5,
    "id": 42,
    "title":"Douglas Adams",
    "body":"foobar"
}

那么定义对象为

[Serializable]
public class UserObject
{
    public int userId;
    public int id;
    public string title;
    public string body;
}

读取格式为

string jsonStrRead = File.ReadAllText(Application.dataPath + "/in.json");
 //!!!关键代码,可与最后的代码进行比较
 // 这里解析的类为 UserObject
UserObject myObject = JsonUtility.FromJson<UserObject>(jsonStrRead);

如果 text 的格式为一堆json对象的列表:

[
    {
        "userId": 5,
        "id": 42,
        "title":"Douglas Adams",
        "body":"foobar"
    },
    {
        "userId": 6,
        "id": 43,
        "title":"Ford",
        "body":"---"
    }
]

那么定义对象为

[Serializable]
public class UserObject
{
    public int userId;
    public int id;
    public string title;
    public string body;
}

[Serializable]
public class RootObject
{
    public UserObject[] users;
}

读取的格式为

string jsonStrRead = File.ReadAllText(Application.dataPath + "/in.json");
 //!!!关键代码,可与前面的代码进行比较
 // 这里解析的类为 RootObject(即 UserObject 组成的数组对象)
 // 先把 jsonStrRead 变成 { "users" jsonStrRead },再从 users 中提取得到 jsonStrRead
UserObject[] myObject = JsonUtility.FromJson<RootObject>("{\"users\":" + jsonStrRead + "}").users;
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

iteapoy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值