私は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 "} {" Apple "、" B " }] 'JSONObjectを作成していたときにJSONArrayとしてそれらを取得できたと考えています。 – RaHuL