有时候需要自动判断解析的json字符串是jsonObject还是JSONArray。因此需要导入net.sf.json的jar包
代码如下
public static void main(String[] args){
//String json ="{\"scm\":{\"key1\":\"vlaue1\",\"key2\":\"vlaue2\"}}";
String json ="{\"scm\":[{\"key1\":\"vlaue1\",\"key1\":\"vlaue2\"},{\"key11\":\"vlaue11\",\"key22\":\"vlaue22\"}]}";
net.sf.json.JSONObject jsonObject =net.sf.json.JSONObject.fromObject(json);
Object listArray = new JSONTokener(jsonObject.getString("scm")).nextValue();
if (listArray instanceof net.sf.json.JSONArray){
net.sf.json.JSONArray jsonArray = (net.sf.json.JSONArray)listArray;
for (int k = 0; k < jsonArray.size(); k++) {
net.sf.json.JSONObject parameterObject = jsonArray.getJSONObject(k);
String string = parameterObject.getString("key1");
System.out.println(string);
}
}else if (listArray instanceof net.sf.json.JSONObject) {
net.sf.json.JSONObject jsonObject3 = (net.sf.json.JSONObject)listArray;
System.out.println(jsonObject3);
}
}