我想用JSONObject在Java中的Json对象中添加一个新对象

cbwuti44  于 2022-10-01  发布在  Java
关注(0)|答案(1)|浏览(270)

我正在尝试创建一个Java应用程序,它使用我发送的数据创建一个json文件,但当我发送新数据时,数据的最后一个数据将被替换

第一个方法称为

az.addUser("John", "10", "star");

JSON

{
   "user" : {
       "name": "john",
       "score": "10",
       "type": "star"
   }
}

第二个方法称为

az.addUser("Kevin", "20", "energy");

JSON预期

{
    "user" : {
       "name": "john",
       "score": "10",
       "type": "star"
   }

    "user" : {
        "name" = "Kevin",
        "score" = "20",
        "type" = "energy"
    }
}

真正的JSON

{  
    "user" : {
        "name" = "Kevin",
        "score" = "20",
        "type" = "Energy"
    }
}

该方法

public void addUser(String name, String score, String type){
    FileWriter wf = new FileWriter("exit.json");
    JSONObject json;
    JSONObject jsonInternal = new JSONObject();

    jsonInternal.put("name", name);
    jsonInternal.put("score", score);
    jsonInternal.put("type", type);

    json = new JSONObject();
    json.put("user", jsonInternal);
    wf.write(json.toJSONString());
    wf.close();

}
pzfprimi

pzfprimi1#

您需要编写JSON数组,而不是JSON对象。下面的代码完全是伪代码,因为我不知道JSONObject来自哪个库。

import java.io.FileWriter;
import java.io.IOException;

public class UserListWriter {
    private String filename;
    private JSONArray usersJson;

    public UserListWriter(String filename) {
        this.filename = filename;
        this.usersJson = new JSONArray();
    }

    public UserListWriter addUser(String name, int score, String type) {
        JSONObject userJson = new JSONObject();
        userJson.put("name", name);
        userJson.put("score", score);
        userJson.put("type", type);
        usersJson.put(userJson);
        return this;
    }

    public UserListWriter write() throws IOException {
        FileWriter wf = new FileWriter(this.filename);
        wf.write(usersJson.toJSONString());
        wf.close();
        return this;
    }

    public static void main(String[] args) {
        try {
            new UserListWriter("exit.json")
                .addUser("John", 10, "star")
                .addUser("Kevin", 20, "energy")
                .write();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

理论输出:

[{
  "name": "John",
  "score": 10,
  "type": "star"
}, {
  "name": "Kevin",
  "score": 20,
  "type": "energy"
}]

相关问题