You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java使用Json Simple库解析含多JSON对象的TXT文件问题

How to Parse Multiple Independent JSON Objects from a TXT File with Json Simple (Java)

Hey there! The issue you're hitting is that your recordings.txt file contains 10 separate JSON objects instead of a single valid JSON structure (like an array wrapped in []). The Json Simple parser expects one valid JSON entity at a time, so trying to parse the entire file in one go will fail.

Here's a reliable, flexible way to split and parse each individual JSON object correctly:

Step-by-Step Solution

We'll use a bracket depth counter to identify the start and end of each JSON object. This method works even if your JSON objects span multiple lines (super common for formatted, human-readable JSON).

Full Code Example

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MultiJsonParser {
    public static void main(String[] args) {
        JSONParser parser = new JSONParser();
        List<JSONObject> jsonObjects = new ArrayList<>();
        
        try (FileReader fr = new FileReader("recordings.txt")) {
            // Read the entire file content into a string first
            StringBuilder fileContentBuilder = new StringBuilder();
            int charRead;
            while ((charRead = fr.read()) != -1) {
                fileContentBuilder.append((char) charRead);
            }
            String fileContent = fileContentBuilder.toString();
            
            int bracketDepth = 0;
            int currentObjectStartIndex = 0;
            
            // Iterate through each character to detect complete JSON objects
            for (int i = 0; i < fileContent.length(); i++) {
                char currentChar = fileContent.charAt(i);
                
                if (currentChar == '{') {
                    bracketDepth++;
                    // Mark the start of a new JSON object if we're at the top level
                    if (bracketDepth == 1) {
                        currentObjectStartIndex = i;
                    }
                } else if (currentChar == '}') {
                    bracketDepth--;
                    // When we return to top level, we've found a complete object
                    if (bracketDepth == 0) {
                        String jsonSubstring = fileContent.substring(currentObjectStartIndex, i + 1);
                        try {
                            JSONObject parsedObj = (JSONObject) parser.parse(jsonSubstring);
                            jsonObjects.add(parsedObj);
                        } catch (ParseException e) {
                            System.err.println("Failed to parse invalid JSON segment: " + jsonSubstring);
                            e.printStackTrace();
                        }
                    }
                }
            }
            
            // Now you can work with your list of parsed JSON objects
            System.out.println("Successfully parsed " + jsonObjects.size() + " JSON objects");
            for (JSONObject obj : jsonObjects) {
                // Example: Print a specific key value (adjust to your JSON structure)
                System.out.println("Object data: " + obj.get("yourTargetKey"));
            }
            
        } catch (IOException e) {
            System.err.println("Error reading the file:");
            e.printStackTrace();
        }
    }
}

Key Details:

  • Bracket Depth Logic: We count opening { and closing } brackets. When the depth returns to 0, we know we've reached the end of a full, valid JSON object.
  • Whitespace Tolerant: This method automatically ignores any spaces, newlines, or tabs between JSON objects—perfect for messy TXT files.
  • Error Isolation: Wrapping individual parse attempts in try-catch means if one JSON object is invalid, the rest can still be parsed successfully.

Simplified Alternative (Single-Line JSON Objects)

If every JSON object is guaranteed to be on its own line (no line breaks within a single object), you can use a simpler line-by-line approach:

// Alternative for single-line JSON objects
try (BufferedReader br = new BufferedReader(new FileReader("recordings.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        line = line.trim();
        if (!line.isEmpty()) {
            try {
                JSONObject obj = (JSONObject) parser.parse(line);
                jsonObjects.add(obj);
            } catch (ParseException e) {
                System.err.println("Skipping invalid line: " + line);
            }
        }
    }
}

This is faster but only works for JSON objects that don't span multiple lines.

内容的提问来源于stack exchange,提问作者Youcef B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:29:20