我正在尝试转换字符串json,其中字符串包含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\"}]";
String grid="{\"grids\":{\"xaxis\":\""+xTable+"},{\"yaxis\":\""+yTable+"},{\"zaxis\":\""+zTable+"}";
String inJson="{\"grid\":\"" +grid + "\"}" ;
JSONObject user = new JSONObject(inJson);
System.out.println(user.getString("grid"));
错误:
Exception in thread "main" org.json.JSONException: Expected a ',' or '}' at 80 [character 81 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:451)
at org.json.JSONObject.<init>(JSONObject.java:231)
at org.json.JSONObject.<init>(JSONObject.java:320)
at JsonExcercise.main(JsonExcercise.java:20)
答案 0 :(得分:1)
它的转义序列下面的问题是
String inJson =&#34; {\&#34; grid \&#34;:\&#39;&#34; + grid +&#34; \&#39;}&#34; ;
答案 1 :(得分:0)
变量grid
和inJson
是错误的json格式,变量中的冗余前引号,并且您可以通过在线Web工具进行验证,以下代码是正确的
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\"}]";
String grid="{\"grids\":[{\"xaxis\":"+xTable+"},{\"yaxis\":"+yTable+"},{\"zaxis\":"+zTable+"}]}";
String inJson="{\"companyid\":\"" +companyid + "\",\"userid\":\"" +userid + "\",\"projectid\":\"" +projectid + "\",\"scenarioid\":" +scenarioid + ",\"grid\":" +grid + "}" ;
JSONObject user = new JSONObject(inJson);
System.out.println(user.getString("companyid"));
你可以学习json数组和json对象
答案 2 :(得分:-1)
你得到的错误是:org.json.JSONException:预期&#39;,&#39;或者&#39;}&#39;
第一步是检查&#39; {&#39;和&#39;}&#39;匹配。
如果你看一下你的代码:
String grid="{\"grids\":{\"xaxis\":\""+xTable+"},{\"yaxis\":\""+yTable+"},{\"zaxis\":\""+zTable+"}";
不平衡,缺少&#39;}&#39;