Unity c# read and write json array (FromJson / ToJson)

Writing of Json (ToJson)

What is written must be a complete object , not an array of objects

ref tojson

Define the object as

[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 reading (FromJson)

It must be a complete object when reading

ref json must represent an object type

If the format of text is a json object:

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

Then define the object as

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

The read format is

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

If the format of text is a list of json objects:

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

Then define the object as

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

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

The read format is

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

Guess you like

Origin blog.csdn.net/iteapoy/article/details/131453147