2

In java how can I pull out the JSON objects enclosed in the "{}"?

I have tried:

JSONObject obj = new JSONObject(jstring);
obj.getJSONArray("fileName");

But it only return the first object. How do I get a list with both objects?

JSON:

[
{
    "fileName": [
        "file1"
    ],
    "date": [
        "8/25/2015 0:00"
    ],
    "time": [
        "7/16/2009 16:51"
    ],
    "id": "1",
    "version_": 1
},
{
    "fileName": [
        "file1"
    ],
    "date": [
        "8/25/2015 0:00"
    ],
    "time": [
        "7/16/2009 16:51"
    ],
    "id": "1",
    "version_": 1
}
]

3 Answers 3

3

Your root JSON is an Array, so first create a JSONArray from your String.

Do this:

JSONArray arr = new JSONArray(jstring);
for (int i = 0; i < arr.length(); i++) { // Walk through the Array.
    JSONObject obj = arr.getJSONObject(i);
    JSONArray arr2 = obj.getJSONArray("fileName");
    // Do whatever.
}

For more info, please refer to the docs on JSONArray and JSONObject.

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

2 Comments

This is incorrect. You can not convert JSONObject to JSONArray. First line needs to be corrected.
Ops. My bad! Done, now it's corrected ;) Thanks for pointing it out. I was typing too fast and forgot to change that from my ctrl + V haha
-1

You have to directly construct JSONArray from JSON string in this case.

JSONArray arr = new JSONArray(jstring);

Comments

-1
JSONArray jsonArray = new JSONArray(jstring); 

1 Comment

Please edit with more information. Code-only and "try this" answers are discouraged, because they contain no searchable content, and don't explain why someone should "try this". We make an effort here to be a resource for knowledge.

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.