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

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;

猜你喜欢

转载自blog.csdn.net/iteapoy/article/details/131453147
今日推荐