java从jsonobject获取jsonarray错误
我正在做一些递归函数调用,以便在JSONObject中追加数据,并最终计算总数 我的JSON结构包含JSONObject和JSONArrayjava从jsonobject获取jsonarray错误,java,json,Java,Json,我正在做一些递归函数调用,以便在JSONObject中追加数据,并最终计算总数 我的JSON结构包含JSONObject和JSONArray { "total": 247, "passed": 247, "failed": 0, "standard_count": [ "LINK_SHUT_NOSHUT", "LC_RELOAD", "VDC_RELOAD", "LINK_FLAP", "SWOVER" ], "submissionFlag": 2, "h
{
"total": 247,
"passed": 247,
"failed": 0,
"standard_count": [
"LINK_SHUT_NOSHUT",
"LC_RELOAD",
"VDC_RELOAD",
"LINK_FLAP",
"SWOVER"
],
"submissionFlag": 2,
"headCount": 6
}
}
在从这个对象获取数据并在下面的标准_count语句代码中计算总数的最后步骤中,我遇到了一个问题
无法将java.lang.Integer强制转换为org.json.JSONArray
代码,我是如何填充上述JSONObject的:
org.json.JSONArray standard_count = new org.json.JSONArray();
org.json.JSONArray sub_mgr_count = subMgrInfo.getJSONArray("standard_count");
org.json.JSONArray mgr_count = mgrInfo.getJSONArray("standard_count");
Set<String> update_standard_set = new HashSet<String>();
for (int i = 0; i < mgr_count.length(); i++) {
update_standard_set.add((String) mgr_count.get(i));
}
for (int i = 0; i < sub_mgr_count.length(); i++) {
update_standard_set.add((String) sub_mgr_count.get(i));
}
standard_count.put(update_standard_set);
mgrInfo.put("total", mgrInfo.getInt("total") + total);
mgrInfo.put("passed", mgrInfo.getInt("passed") + passed);
mgrInfo.put("failed", mgrInfo.getInt("failed") + failed);
mgrInfo.put("headCount", mgrInfo.getInt("headCount") + headCount + 1);
mgrInfo.put("submissionFlag", mgrInfo.getInt("submissionFlag") + submissionFlag);
mgrInfo.remove("standard_count");
mgrInfo.put("standard_count", standard_count.get(0));
确保没有任何内容正在修改对象,并且您正确地访问了对象。我使用以下代码对您提供的json对象进行测试,该代码工作正常:
public static void main (String args[]) throws JSONException{
String jsonString = "{ \"total\": 247, \"passed\": 247, \"failed\": 0, \"standard_count\": [ \"LINK_SHUT_NOSHUT\", \"LC_RELOAD\", \"VDC_RELOAD\", \"LINK_FLAP\", \"SWOVER\" ], \"submissionFlag\": 2, \"headCount\": 6 }";
JSONObject newMgrObj = new JSONObject(jsonString);
JSONArray standard_count = newMgrObj.getJSONArray("standard_count");
System.out.println(standard_count.toString());
}
这给了我输出:
["LINK_SHUT_NOSHUT","LC_RELOAD","VDC_RELOAD","LINK_FLAP","SWOVER"]
@我试着直接把更新设置成标准设置。从JSONObject检索时,它给了我相同的错误。因此,为了确保附加了JSONArray对象,我显式定义了standard_count并发送该JSONArray的第一个元素。无论我做什么,它都会抛出错误。有趣的是,它并不总是失败。仅偶尔出现一次:在mgrInfo点和mgrObj点之间,可能有任何其他源正在操作标准_count属性,或者mgrObj不是由mgrInfo表示的同一资源。事实上,你只是偶尔会遇到这种失败,这让我倾向于使用现有上下文中不存在的条件逻辑。
public static void main (String args[]) throws JSONException{
String jsonString = "{ \"total\": 247, \"passed\": 247, \"failed\": 0, \"standard_count\": [ \"LINK_SHUT_NOSHUT\", \"LC_RELOAD\", \"VDC_RELOAD\", \"LINK_FLAP\", \"SWOVER\" ], \"submissionFlag\": 2, \"headCount\": 6 }";
JSONObject newMgrObj = new JSONObject(jsonString);
JSONArray standard_count = newMgrObj.getJSONArray("standard_count");
System.out.println(standard_count.toString());
}
["LINK_SHUT_NOSHUT","LC_RELOAD","VDC_RELOAD","LINK_FLAP","SWOVER"]