Java如何读取JSON文件全部JSON对象?遍历重复输出同一对象如何解决
问题原因
- JSON格式不合法:你当前的JSON文件是多个独立对象直接用逗号分隔,没有外层包裹数组符号
[],解析时只会识别到第一个对象,后续内容会被忽略。 - 代码逻辑错误:
- 同时用两套JSON解析工具(org.json的JSONObject和Jackson的ObjectMapper)重复解析,逻辑冗余
- 循环遍历的是第一个解析出来的对象的键集合(包含
id、score、ip、message四个键,刚好循环4次),但每次取值都从固定的第一个jo对象中读取,自然每次输出内容都相同 - 没有正确识别JSON结构为数组,错误将数组类型的JSON解析为HashMap类型
修复步骤
1. 修正JSON格式
给所有对象外层添加数组符号[],修改后的JSON内容如下:
[ { "id": "test", "score": 12, "ip": "1.2.3.4", "message": "Hi" }, { "id": "test", "score": 5, "ip": "1.2.3.5" }, { "id": "test", "score": 17, "ip": "1.2.3.4" }, { "id": "test2", "score": 9, "ip": "1.2.3.4" } ]
2. 修正代码逻辑
仅保留Jackson作为解析工具,将JSON数组解析为List集合后遍历:
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.Map; public class ReadIpJson { public static void main(String[] args) throws Exception { String file = "src/main/resources/ip.json"; String json = readFileAsString(file); ObjectMapper objectMapper = new ObjectMapper(); // 按JSON数组结构解析为List<Map> List<Map<String, Object>> ipList = objectMapper.readValue(json, new TypeReference<List<Map<String, Object>>>() {}); // 遍历数组内的每一个对象 for (Map<String, Object> ipInfo : ipList) { String id = (String) ipInfo.get("id"); System.out.println(id); String ip = (String) ipInfo.get("ip"); System.out.println(ip); Integer score = (Integer) ipInfo.get("score"); System.out.println(score); } } public static String readFileAsString (String file) throws IOException { return new String(Files.readAllBytes(Paths.get(file))); } }
如果需要更规范的使用,建议定义对应属性的实体类接收解析结果,比用Map类型更安全方便。
内容的提问来源于stack exchange,提问作者Water4Summer
相关产品推荐
相关产品推荐

