JamEngulfer
JamEngulfer

Reputation: 747

Accessing JSON array node inside an object

I've been having trouble with accessing a JSON array node inside another object.

The JSON file I'm trying to read basically looks like this:

[
{
  "dependencies": [ "data"
  ]
}
]

I've got to the point where I'm unable to access the tag using the code I have and I've got no idea how.

I'm using the JSON library from http://www.json.org/java/

The full code that I've used in this example is here:

    List depList;

    InputStream is = new URL(url).openStream();

    BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
    JdomParser jp = new JdomParser();
    JsonRootNode js = jp.parse(rd);

    if(js.getArrayNode(0).get(0).getArrayNode("dependencies").size() > 0){
        depList = js.getArrayNode(0).get(0).getArrayNode("dependencies");
        is.close();
        return depList;
    } else {
        return null;
    }

The specific line that I'm using is this one: js.getArrayNode(0).get(0).getArrayNode("dependencies")

Upvotes: 0

Views: 1870

Answers (2)

Eng.Fouad
Eng.Fouad

Reputation: 117665

JSONArray outArray = new JSONArray(json);
JSONObject outObject = outArray.getJSONObject(0);
JSONArray inArray = outObject.getJSONArray("dependencies");
String data = inArray.getString(0);

Upvotes: 1

Daniel Kaplan
Daniel Kaplan

Reputation: 67494

Here's some sample code that should help you. This prints out "data".

package com.sandbox;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Sandbox {
    public static void main(String[] args) throws JSONException {
        String input = "[\n" +
                "{\n" +
                "  \"dependencies\": [ \"data\"\n" +
                "  ]\n" +
                "}\n" +
                "]";

        JSONArray start = new JSONArray(input);
        JSONObject jsonObject = start.getJSONObject(0);
        JSONArray dependencies = jsonObject.getJSONArray("dependencies");
        String data = dependencies.getString(0);
        System.out.println(data);
    }

}

Here's my maven dependency:

    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20090211</version>
    </dependency>

Upvotes: 0

Related Questions