如何在Java中将JSONArray(splits字段)转换为JSON字段?
解决方案:将JSON中splits数组转换为独立sector字段
你可以直接使用Jackson的ObjectNode对原有JSON节点进行原地修改,无需创建新的实体类或对象,步骤如下:
实现代码
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.IOException; public class JsonSplitConverter { public static void main(String[] args) throws IOException { // 输入的JSON字符串(外层需包裹为数组) String inputJson = "[\n" + " {\n" + " \"carId\": 1001,\n" + " \"driverIndex\": 0,\n" + " \"laptime\": 173001,\n" + " \"isValidForBest\": false,\n" + " \"splits\": [\n" + " 91851,\n" + " 52002,\n" + " 29147\n" + " ]\n" + " },\n" + " {\n" + " \"carId\": 1001,\n" + " \"driverIndex\": 0,\n" + " \"laptime\": 107270,\n" + " \"isValidForBest\": true,\n" + " \"splits\": [\n" + " 26295,\n" + " 51960,\n" + " 29015\n" + " ]\n" + " }\n" + "]"; ObjectMapper mapper = new ObjectMapper(); ArrayNode rootArray = (ArrayNode) mapper.readTree(inputJson); // 遍历每个JSON对象节点 for (JsonNode node : rootArray) { if (node instanceof ObjectNode objectNode) { // 获取splits数组节点 ArrayNode splitsArray = (ArrayNode) objectNode.get("splits"); // 依次添加sector字段 if (splitsArray.size() >= 1) { objectNode.put("sector1", splitsArray.get(0).asLong()); } if (splitsArray.size() >= 2) { objectNode.put("sector2", splitsArray.get(1).asLong()); } if (splitsArray.size() >= 3) { objectNode.put("sector3", splitsArray.get(2).asLong()); } // 删除原splits字段 objectNode.remove("splits"); } } // 输出格式化后的结果JSON String outputJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootArray); System.out.println(outputJson); } }
代码说明
- 用
ObjectMapper将输入JSON解析为ArrayNode,适配你的多对象输入结构 - 遍历每个
ObjectNode,直接在原节点上做修改,完全不需要新建对象 - 从
splits数组中提取元素,映射为sector1/sector2/sector3字段 - 最后移除无用的
splits字段,完成转换 - 格式化输出的JSON结构与你期望的完全一致
内容的提问来源于stack exchange,提问作者Kowal998
相关产品推荐
相关产品推荐

