vlio20
vlio20

Reputation: 9295

java nested JSONArray

I want to know if it is possible to check if some key exists in some jsonArray using java. For example: lets say that I have this json string:

{'abc':'hello','xyz':[{'name':'Moses'}]}

let's assume that this array is stored in jsnArray from Type JSONArray. I want to check if 'abc' key exists in the jsnArray, if it exists I should get true else I should get false (in the case of 'abc' I should get true). Thnkas

Upvotes: 0

Views: 9303

Answers (4)

Vito Gentile
Vito Gentile

Reputation: 14366

What you posted is a JSONObject, inside which there is a JSONArray. The only array you have in this example is the array 'xyz', that contains only one element.

A JSONArray example is the following one:

{
 'jArray':
          [
           {'hello':'world'},
           {'name':'Moses'},
           ...
           {'thisIs':'theLast'}
          ]
}

You can test if a JSONArray called jArray, included inside a given JSONObject (a situation similar to the example above) contains the key 'hello' with the following function:

boolean containsKey(JSONObject myJsonObject, String key) {
    boolean containsHelloKey = false;
    try {
        JSONArray arr = myJsonObject.getJSONArray("jArray");
        for(int i=0; i<arr.length(); ++i) {
            if(arr.getJSONObject(i).get(key) != null) {
               containsHelloKey = true;
               break;
            }
        }
    } catch (JSONException e) {}

    return containsHelloKey;
}

And calling that in this way:

containsKey(myJsonObject, "hello");

Upvotes: 2

Piyas De
Piyas De

Reputation: 1764

If you use JSON Smart Library in Java to parse JSon String -

You can parse JSon Array with following code snippet -

like -

JSONObject resultsJSONObject = (JSONObject) JSONValue.parse(<<Fetched JSon String>>);
JSONArray dataJSon = (JSONArray) resultsJSONObject.get("data");
JSONObject[] updates = dataJSon.toArray(new JSONObject[dataJSon.size()]);

for (JSONObject update : updates) {
            String message_id = (String) update.get("message_id");
            Integer author_id = (Integer) update.get("author_id");
            Integer createdTime = (Integer) update.get("created_time");
            //Do your own processing...
            //Here you can check null value or not..
}

You can have more information in - https://code.google.com/p/json-smart/

Hope this help you...

Upvotes: 1

not_john
not_john

Reputation: 170

JSON arrays don't have key value pairs, JSON objects do.

If you store it as a json object you can check the keys using this method: http://www.json.org/javadoc/org/json/JSONObject.html#has(java.lang.String)

Upvotes: 1

mkrnr
mkrnr

Reputation: 900

Using regular expressions will not work because of the opening and closing brackets.

You could use a JSON library (like google-gson) to transform your JSON Array into a java array and then handle it.

Upvotes: 1

Related Questions