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

如何在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 10:51:23