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;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
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);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
Json 的读取 (FromJson)
读取的时候一定要是一个完整的 object
如果 text 的格式为一个json对象:
{
"userId": 5,
"id": 42,
"title":"Douglas Adams",
"body":"foobar"
}
- 1
- 2
- 3
- 4
- 5
- 6
那么定义对象为
[Serializable]
public class UserObject
{
public int userId;
public int id;
public string title;
public string body;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
读取格式为
string jsonStrRead = File.ReadAllText(Application.dataPath + "/in.json");
//!!!关键代码,可与最后的代码进行比较
// 这里解析的类为 UserObject
UserObject myObject = JsonUtility.FromJson<UserObject>(jsonStrRead);
- 1
- 2
- 3
- 4
如果 text 的格式为一堆json对象的列表:
[
{
"userId": 5,
"id": 42,
"title":"Douglas Adams",
"body":"foobar"
},
{
"userId": 6,
"id": 43,
"title":"Ford",
"body":"---"
}
]
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
那么定义对象为
[Serializable]
public class UserObject
{
public int userId;
public int id;
public string title;
public string body;
}
[Serializable]
public class RootObject
{
public UserObject[] users;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
读取的格式为
string jsonStrRead = File.ReadAllText(Application.dataPath + "/in.json");
//!!!关键代码,可与前面的代码进行比较
// 这里解析的类为 RootObject(即 UserObject 组成的数组对象)
// 先把 jsonStrRead 变成 { "users" jsonStrRead },再从 users 中提取得到 jsonStrRead
UserObject[] myObject = JsonUtility.FromJson<RootObject>("{\"users\":" + jsonStrRead + "}").users;
- 1
- 2
- 3
- 4
- 5
评论记录:
回复评论: