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

Java中含JSON对象与数组的字符串转JSON报错排查

解决JSON字符串拼接导致的JSONException错误

你遇到的这个org.json.JSONException完全是因为手动拼接JSON字符串时的格式错误导致的,咱们先拆解问题出在哪,再给你两种修复方案。

错误原因分析

你的代码里grid字符串的拼接逻辑存在两处致命问题:

  • 嵌套对象语法错误:你试图构建包含grids的对象,但错误地在yaxis和zaxis前额外加了{,这完全破坏了JSON对象的结构——xaxis、yaxis、zaxis都是grids对象的属性,不需要额外的花括号包裹。
  • 括号/引号不匹配:拼接后的字符串缺少多个闭合的},导致JSON解析器无法识别完整的结构,所以才会抛出Expected a ',' or '}'的错误。

修复方案1:修正手动拼接的字符串

如果一定要用手动拼接的方式,需要严格按照JSON格式来编写拼接逻辑:

String companyid="14";
String userid="1002";
String projectid="378";
String scenarioid="1";
String xTable = "[{\"Label\":\"A\",\"Dimension\":\"0\"},{\"Label\":\"B\",\"Dimension\":\"10\"}]";
String yTable = "[{\"Label\":\"1\",\"Dimension\":\"0\"},{\"Label\":\"2\",\"Dimension\":\"10\"}]";
String zTable = "[{\"Label\":\"Floor1\",\"Dimension\":\"0\"},{\"Label\":\"Floor2\",\"Dimension\":\"10\"}]";
// 修正grids的结构:每个属性直接用逗号分隔,最后闭合所有花括号
String grid="{\"grids\":{\"xaxis\":"+xTable+",\"yaxis\":"+yTable+",\"zaxis\":"+zTable+"}}";
String inJson="{\"grid\":" +grid + "}" ;
JSONObject user = new JSONObject(inJson);
System.out.println(user.getString("grid"));

修复方案2:使用JSON API构建(推荐)

手动拼接JSON字符串很容易出现转义、括号匹配的问题,更稳妥的方式是直接用org.json库的JSONObject和JSONArray来构建结构,API会自动处理格式问题:

String companyid="14";
String userid="1002";
String projectid="378";
String scenarioid="1";

// 构建x轴的数组
JSONArray xArray = new JSONArray();
xArray.put(new JSONObject().put("Label", "A").put("Dimension", "0"));
xArray.put(new JSONObject().put("Label", "B").put("Dimension", "10"));

// 构建y轴的数组
JSONArray yArray = new JSONArray();
yArray.put(new JSONObject().put("Label", "1").put("Dimension", "0"));
yArray.put(new JSONObject().put("Label", "2").put("Dimension", "10"));

// 构建z轴的数组
JSONArray zArray = new JSONArray();
zArray.put(new JSONObject().put("Label", "Floor1").put("Dimension", "0"));
zArray.put(new JSONObject().put("Label", "Floor2").put("Dimension", "10"));

// 构建grids对象
JSONObject grids = new JSONObject();
grids.put("xaxis", xArray);
grids.put("yaxis", yArray);
grids.put("zaxis", zArray);

// 构建外层的JSON对象
JSONObject inJson = new JSONObject();
inJson.put("grid", grids);

// 输出结果
System.out.println(inJson.getJSONObject("grid").toString());

这种方式不仅避免了手动拼接的失误,代码可读性和可维护性也更高,后续修改结构时更方便。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:46:45