Ani
Ani

Reputation: 608

Extract JSON Keynames in Java

I want to extract JSON structure (only keyNames structure) by preserving the hierarchy (parent child relationship); I don't want values from the JSON yet. I am new to Java and have been tying to achieve this using Jackson , but with no success.

Any direction on this will be much appreciated.

Upvotes: 1

Views: 114

Answers (2)

Mr. Kevin Thomas
Mr. Kevin Thomas

Reputation: 847

I created a static inner class for you by using JSONObject (http://www.json.org/javadoc/org/json/JSONObject.html)

public static class KeyNode {
    private String name;
    private ArrayList<KeyNode> children;

    public KeyNode(String name) {
        this.name = name;
        this.children = new ArrayList<KeyNode>();
    }

    public void addChild(KeyNode child) {
        this.children.add(child);
    }

    public static void parseJsonToKeys(KeyNode node, JSONObject json) throws JSONException {
        Iterator<?> keys = json.keys();
        while (keys.hasNext()) {
            String name = (String) keys.next();
            KeyNode child = new KeyNode(name);
            node.addChild(child);
            if (json.optJSONObject(name) != null) {
                parseJsonToKeys(child, json.getJSONObject(name));
            } else if (json.optJSONArray(name) != null) {
                JSONArray array = json.getJSONArray(name);
                for (int i = 0; i < array.length(); i++) {
                    try {
                        array.getJSONObject(i);
                        parseJsonToKeys(child, json.getJSONObject(name));
                    } catch (JSONException e) {
                        // this is ok
                    }
                }
            }
        }
    }

    public static void exampleCodeUsage() {
        try {
            JSONObject json = new JSONObject("your json");
            KeyNode keyHierarchy = new KeyNode("root");
            parseJsonToKeys(keyHierarchy, json);
        } catch (JSONException e) {
            // your json is not formatted correctly
        }
    }
}

Upvotes: 1

Santhosh
Santhosh

Reputation: 1791

JSONParser parser = parser;
Object obj = parser.parse(new FileReader(FileName.Json));
JSONObject jobj = (JSONObject) obj;

obj.keys()

The method will give you the list of all keys in JSONObject

Upvotes: 0

Related Questions