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

Java中将无效JSON转换为有效JSON的实现方案

处理非标准JSON格式的Java方案

针对你拿到的这种非标准格式数据,这里提供两种可靠的Java处理思路,把它转换成标准JSON数组:

方法一:正则表达式批量替换(格式固定时首选)

这种方法适合数据格式稳定的场景,通过正则快速修正格式问题:

步骤代码示例

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonArray;

public class JsonFixer {
    public static void main(String[] args) throws Exception {
        // 原始非标准字符串
        String rawData = "[489078:{cancelled:1, totalQty:2, AcceptedQty:1}, 489079:{cancelled:0, totalQty:1, AcceptedQty:1}, ...]";
        
        // 1. 清理冗余内容:去掉前后的[]、省略号...,并去除多余空格
        String cleaned = rawData.replaceAll("^\\[|\\]$", "")
                               .replaceAll("\\.\\.\\.", "")
                               .trim();
        
        // 2. 把数字ID包装成对象属性:比如489078:{ 替换为 {"id":489078,
        String withIdField = cleaned.replaceAll("(\\d+):\\{", "{\"id\":$1, ");
        
        // 3. 给所有对象键添加双引号:比如cancelled: 替换为 "cancelled":
        String validJson = "[" + withIdField.replaceAll("([^:,\\s]+):", "\"$1\":") + "]";
        
        // 4. 解析为标准JsonArray
        ObjectMapper mapper = new ObjectMapper();
        JsonArray jsonArray = mapper.readTree(validJson).getAsJsonArray();
        
        // 遍历示例
        for (JsonNode node : jsonArray) {
            int id = node.get("id").asInt();
            int cancelled = node.get("cancelled").asInt();
            System.out.printf("ID: %d, 取消状态: %d%n", id, cancelled);
        }
    }
}

方法二:逐段手动解析(格式易变时更可靠)

如果正则容易因为格式微小变化失效,可以手动拆分每个条目处理:

步骤代码示例

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonArray;

public class JsonParser {
    public static void main(String[] args) throws Exception {
        String rawData = "[489078:{cancelled:1, totalQty:2, AcceptedQty:1}, 489079:{cancelled:0, totalQty:1, AcceptedQty:1}, ...]";
        
        // 清理基础内容
        String cleaned = rawData.replaceAll("^\\[|\\]$", "")
                               .replaceAll("\\.\\.\\.", "")
                               .trim();
        
        // 按条目拆分:用正向预查确保分割符后是数字ID开头的条目
        String[] entries = cleaned.split(",(?=\\d+:)");
        
        JsonArray resultArray = new JsonArray();
        ObjectMapper mapper = new ObjectMapper();
        
        for (String entry : entries) {
            entry = entry.trim();
            // 拆分ID和对象内容部分
            int colonPos = entry.indexOf(':');
            String idStr = entry.substring(0, colonPos).trim();
            String rawObj = entry.substring(colonPos + 1).trim();
            
            // 给对象内的键加双引号
            String fixedObj = rawObj.replaceAll("([^:,\\s]+):", "\"$1\":");
            // 拼接成完整的对象字符串
            String fullObjStr = "{\"id\":" + idStr + ", " + fixedObj.substring(1, fixedObj.length() - 1) + "}";
            
            // 解析为JsonNode并加入数组
            JsonNode node = mapper.readTree(fullObjStr);
            resultArray.add(node);
        }
        
        // 使用resultArray进行后续处理
    }
}

注意事项

  • 如果数据中的键包含特殊字符(比如空格、下划线以外的符号),需要调整正则表达式,把([^:,\\s]+)替换为更匹配实际键格式的规则
  • 示例使用Jackson库解析JSON,如果你用Gson,只需替换解析部分为JsonArray jsonArray = JsonParser.parseString(validJson).getAsJsonArray();即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 09:07:37