我正在使用json-simple-1.1.jar 並嘗試從代碼中顯示的json中獲取多個(至少3個)值部分。[Java]:無法解析無數組/子數組的JSON
我的代碼適用於具有多個數組的JSON,但不適用於簡單的json格式。
{
"Addresses": {
"UserName": "Rahul",
"Status": "Active",
"CreateDate": "2017-01-09T11:39:31.244Z",
"SecretAccessKey": "ABCD-EFGH-HIJK",
"AccessKeyId": "1234567"
}
}
以下是我試圖使用java邏輯:
public static String[] getValuesFromJson(String filename, Object key, int exp_sizeOfArray, String[] exp_keys) throws FileNotFoundException, IOException, ParseException {
String valuesFromJson[] = new String[exp_keys.length];
/** Create a JSONParser object*/
JSONParser parser = new JSONParser();
/** Read the JSON file using parser*/
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader(
filename));
System.out.println("JsonObject size: "+jsonObject.keySet().size());
for (Object object : jsonObject.keySet()) {
System.out.println(jsonObject.get(object.toString()));
}
/** Get the values in JSONArray using the key*/
JSONArray jsonArray = (JSONArray) jsonObject.get(key);
for (int i = 0; i < jsonArray.size(); i++) {
/** Add the individual set from JSONArray to a JSONObject */
JSONObject subJsonObject = (JSONObject) parser.parse(jsonArray.get(i).toString());
/** Check for expected size of array */
if(subJsonObject.size() <= exp_sizeOfArray){
int index=0;
/** Check for each key value in the sub-JSONObject keySet*/
for (Object object : subJsonObject.keySet()) {
/** Iterate until the expected key value matches with the actual value*/
for (int j = 0; j < exp_keys.length; j++) {
/** Check if the expected key matches with any of the key value*/
if(object.toString().trim().equals(exp_keys[j].toString().trim())){
System.out.println("Key: '".concat(object.toString()).concat("'\tValue: '").concat(subJsonObject.get(object)+"'"));
valuesFromJson[index] = subJsonObject.get(exp_keys[j]).toString();
index++;
break;
}
}
}
}
}
/** Return the value of expected key*/
return valuesFromJson;
}
我得到錯誤: 「org.json.simple.JSONObject不能轉換爲org.json.simple.JSONArray」下面一行:
JSONArray jsonArray = (JSONArray) jsonObject.get(key);
似乎不言自明。你正在嘗試讀取一個沒有的數組。你的問題是什麼? – shmosel
如果我可能會問,爲什麼你覺得在你的JSON代碼中總是有一個數組? –
呃......我以前的json格式是這樣的:'{地址:[{「One」:「1」,「Two」:「2」} {「A」:「Apple」,「B」 }]'所以我正在考慮我能夠獲取那些作爲JSONArray而我創造了JSONObject – RaHuL