Java中如何读取多个JSON?如何生成合法JSON数组?
Hey there! Let's work through your Java JSON problems—first fixing that invalid output you're getting, then covering how to properly read multiple JSON entries.
The issue right now is that you're writing individual JSONObject instances directly one after another, which creates invalid JSON (two separate objects glued together). To get that valid JSON array format you need, you should wrap your user objects in a JSONArray instead.
Here's how to adjust your code:
Step 1: Create a JSONArray to hold your user objects
// Initialize an empty array to store all user entries JSONArray userArray = new JSONArray();
Step 2: Add each user's JSONObject to the array
// Create first user object JSONObject user1 = new JSONObject(); user1.put("User_id", jTextField1.getText()); // Note: jPasswordField.getPassword() returns a char[]—convert it to String properly user1.put("Password", new String(jPasswordField1.getPassword())); userArray.put(user1); // Create second user object (repeat this for additional users, or use a loop) JSONObject user2 = new JSONObject(); user2.put("User_id", "test122"); user2.put("Password", "asds"); userArray.put(user2);
Step 3: Write the JSONArray to your file
When you call toString() on the JSONArray, it will output the valid array format you need:
String filename = "json_log_text.json"; Files.write(Paths.get(filename), userArray.toString().getBytes());
If you need to append new users to an existing file:
You can't just tack a new object onto the end—you need to read the existing array, add the new user, then rewrite the file:
File jsonFile = new File("json_log_text.json"); JSONArray existingArray = new JSONArray(); // Read existing array if the file exists and isn't empty if (jsonFile.exists() && jsonFile.length() > 0) { String fileContent = new String(Files.readAllBytes(jsonFile.toPath())); existingArray = new JSONArray(fileContent); } // Add new user to the array JSONObject newUser = new JSONObject(); newUser.put("User_id", jTextField1.getText()); newUser.put("Password", new String(jPasswordField1.getPassword())); existingArray.put(newUser); // Rewrite the updated array to the file Files.write(jsonFile.toPath(), existingArray.toString().getBytes());
How you read depends on whether your file has a valid JSON array or (like your old output) multiple standalone JSON objects.
Scenario 1: Reading a valid JSON array file
This is straightforward—parse the entire file into a JSONArray and iterate through each object:
String fileContent = new String(Files.readAllBytes(Paths.get("json_log_text.json"))); JSONArray userArray = new JSONArray(fileContent); // Loop through each user entry for (int i = 0; i < userArray.length(); i++) { JSONObject user = userArray.getJSONObject(i); String userId = user.getString("User_id"); String password = user.getString("Password"); // Do something with the data (e.g., print, store in a list) System.out.println("User ID: " + userId + ", Password: " + password); }
Scenario 2: Reading a file with multiple standalone JSON objects
If you're dealing with the old invalid format (objects glued together), you can use a regex to extract each individual JSON object and parse them one by one:
String fileContent = new String(Files.readAllBytes(Paths.get("invalid_json.txt"))); // Regex to match each JSON object wrapped in {} Pattern jsonPattern = Pattern.compile("\\{[^}]*\\}"); Matcher matcher = jsonPattern.matcher(fileContent); // Extract and parse each object while (matcher.find()) { String singleJson = matcher.group(); JSONObject user = new JSONObject(singleJson); String userId = user.getString("User_id"); String password = user.getString("Password"); System.out.println("User ID: " + userId + ", Password: " + password); }
内容的提问来源于stack exchange,提问作者Atul

