0

I am using the json-simple-1.1.jar and trying to get multiple (atleast 3) values from the json as shown in the code section.

My code works for a JSON with multiple arrays but not working for simple json format.

{
"Addresses": {
    "UserName": "Rahul", 
    "Status": "Active", 
    "CreateDate": "2017-01-09T11:39:31.244Z", 
    "SecretAccessKey": "ABCD-EFGH-HIJK", 
    "AccessKeyId": "1234567"
 }
}

Following is the java logic I am trying to use:

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;
}

I am getting error: "org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray" on below line:

JSONArray jsonArray = (JSONArray) jsonObject.get(key);
3
  • 1
    Seems pretty self-explanatory. You're trying to read an array where there is none. What is your question? Commented Jan 10, 2017 at 7:06
  • If I may ask, why is it that you think there's always an array in your JSON code? Commented Jan 10, 2017 at 7:49
  • Well... My previous json format was like: { Addresses: [{"One" : "1", "Two" : "2"} {"A" : "Apple", "B":"Ball"}] So I am considering I was able to fetch those as a JSONArray whn I was creaing the JSONObject Commented Jan 10, 2017 at 7:51

2 Answers 2

1

You are trying to cast JSONObject to JSONArray, but there is no array. Rather get all object keys and iterate over it.

If you go to json.org(1) you can find there:

An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma)

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, array is a collection of values, "And not of <key, value>" like hashmap. Actually I am trying to put the values under JSONObject to the JSONArray to iterate it. Even jsonObject.keySet() is giving "Addresses" as the result. :-(
I got your point about no array in my json. Then how should I fetch the key-value pairs from the JSON? Can you please help me with the code?
Go one level down. You have object in object.
0

Voila! Done it without converting JSONObject to JSONArray

JSONObject jsonObject = (JSONObject) parser.parse(new FileReader(
            filename));
    /** Creating another JSONObject here */
    JSONObject jsonObject2 = (JSONObject) parser.parse(jsonObject.get(key).toString());
    for (Object newKey : jsonObject2.keySet()) {
        System.out.println("Key: '".concat(newKey.toString()).concat("'\tValue: '").concat(jsonObject2.get(newKey)+"'"));
    }

Thank you guys for the help!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.