5

This is the program i wrote:

    /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

/**
 *
 * @author 311001
 */
public class NewClass {

    public static void main(String args[]) {
        JSONObject parentData = new JSONObject();
        JSONObject childData = new JSONObject();
        try {

            parentData.put("command", "login");
            parentData.put("uid", "123123123");
            childData.put("uid", "007");
            childData.put("username", "sup");
            childData.put("password", "bros");
            parentData.put("params", childData);
            System.out.println(parentData);

            Map<String, String> map = new HashMap<>();
            Iterator<?> iter = parentData.keys();
            while (iter.hasNext()) {
                String key = (String) iter.next();
                String value = parentData.getString(key);
                map.put(key, value);
            }

            for (Entry<String, String> entry : map.entrySet()) {
                System.out.println("key > " + entry.getKey() + "  : value = " + entry.getValue());
            }

            String testData = map.get("params.uid");
            System.out.println(testData);
            System.out.println("Tokenizing json");
            String resultStr = parentData.toString();
            System.out.println("String tokens ");
            StringTokenizer st = new StringTokenizer(resultStr);
            System.out.println(st.countTokens());
            while (st.hasMoreTokens()) {
                System.out.println(st.nextToken());
            }
            String testDat="abc :: result";
            StringTokenizer simpleString = new StringTokenizer(testDat);
            System.out.println("Tokenizing simple string");
            System.out.println(simpleString.countTokens());
            while (simpleString.hasMoreTokens()) {
                System.out.println(simpleString.nextToken());
            }


        } catch (JSONException e) {
            e.printStackTrace();
        }


    }
}

the output i got:

run:
{"command":"login","uid":"123123123","params":{"uid":"007","username":"sup","password":"bros"}}
key > uid  : value = 123123123
key > command  : value = login
key > params  : value = {"uid":"007","username":"sup","password":"bros"}
null
Tokenizing json
String tokens 
1
{"command":"login","uid":"123123123","params":{"uid":"007","username":"sup","password":"bros"}}
Tokenizing simple string
3
abc
::
result
BUILD SUCCESSFUL (total time: 0 seconds)

How can I recieve all the keys in my json object. In case I tokenize why do i get only one string token while for a simple string am getting the correct output 3 tokens.

Aayush
  • 1,244
  • 5
  • 19
  • 48
  • can you please explain why are you using map.get("params.uid") and not map.get("params").get("uid"); – faizan Jan 31 '13 at 06:42
  • thats a mistake ! I should be using map.get("params").get("uid").But what i need is a list of all the keys in my json. – Aayush Jan 31 '13 at 06:46
  • @faizan In case i have a method which accepts a complex nested json object, how do i find all the keys in that jsob object ? – Aayush Jan 31 '13 at 06:47
  • @faizan tried out what you said am getting an error for map.get("params").get("uid"); – Aayush Jan 31 '13 at 06:51
  • you can recursively go through the map of json object – faizan Jan 31 '13 at 07:01
  • call the same function when your map.get(key).getClass()==JSONObject.Class – faizan Jan 31 '13 at 07:02

4 Answers4

5

You can recursively traverse your JsonObject to get all keys. heres the pseudocode

findKeys(JsonObject obj,List keys){
List<String>keysFromObj=obj.keys();
keys.addAll(keysFromObj);
for(String key:keysFromObj){
    if(obj.get(key).getClass()==JSONObject.class){
         findKeys(obj.get(key),keys);
         }
    }
}

So suppose if your object is {"a":1,"b":{"c":"hello","d":4.0}} the above function should give you ["a","b","c","d"]

But if you want only ["a","c","d"] as your output,you can write-

findKeys(JsonObject obj,List keys){
List<String>keysFromObj=obj.keys();

for(String key:keysFromObj){
    if(obj.get(key).getClass()==JSONObject.class){
         findKeys(obj.get(key),keys);
         }else{
         keys.add(key);
         }
    }
}
faizan
  • 680
  • 1
  • 6
  • 15
3

I am late to the party, but I am adding here my solution:

Input:

{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

Retrieve all unique keys:

public static void findAllKeys(Object object, Set<String> finalKeys) {
        if (object instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) object;

            jsonObject.keySet().forEach(childKey -> {
                finalKeys.add(childKey);
                findAllKeys(jsonObject.get(childKey), finalKeys);
            });
        } else if (object instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) object;

            IntStream.range(0, jsonArray.length())
                    .mapToObj(jsonArray::get)
                    .forEach(o -> findAllKeys(o, finalKeys));
        }
    }

Usage:

Set<String> finalKeys = new HashSet<>();
findAllKeys(new JSONObject(str), finalKeys);
System.out.println(finalKeys);

Output:

[
  GlossEntry,
  GlossSee,
  SortAs,
  GlossList,
  title,
  GlossDiv,
  glossary,
  GlossTerm,
  GlossDef,
  para,
  GlossSeeAlso,
  ID,
  Acronym,
  Abbrev
]

Retrieve all unique "full path" keys:

public void findAllKeys(Object object, String key, Set<String> finalKeys) {
    if (object instanceof JSONObject) {
        JSONObject jsonObject = (JSONObject) object;

        jsonObject.keySet().forEach(childKey -> {
            findAllKeys(jsonObject.get(childKey), key != null ? key + "." + childKey : childKey, finalKeys);
        });
    } else if (object instanceof JSONArray) {
        JSONArray jsonArray = (JSONArray) object;
        finalKeys.add(key);

        IntStream.range(0, jsonArray.length())
                .mapToObj(jsonArray::get)
                .forEach(jsonObject -> findAllKeys(jsonObject, key, finalKeys));
    }
    else{
        finalKeys.add(key);
    }
}

Usage:

Set<String> finalKeys = new HashSet<>();
findAllKeys(new JSONObject(jsonStr), null, finalKeys);
System.out.println(finalKeys);

Output:

[
  glossary.GlossDiv.GlossList.GlossEntry.ID,
  glossary.title,
  glossary.GlossDiv.GlossList.GlossEntry.GlossSee,
  glossary.GlossDiv.GlossList.GlossEntry.GlossTerm, 
  glossary.GlossDiv.GlossList.GlossEntry.Acronym, 
  glossary.GlossDiv.GlossList.GlossEntry.Abbrev, 
  glossary.GlossDiv.GlossList.GlossEntry.GlossDef.para, 
  glossary.GlossDiv.GlossList.GlossEntry.SortAs, 
  glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso,
  glossary.GlossDiv.title
]
Most Noble Rabbit
  • 2,728
  • 2
  • 6
  • 12
2

Here is one implementation using org.json not org.json.simple

It finds all unique values of a json with the Key:value combination using java.

Input json:

{
    d: {
        results: [{
            __metadata: {
                uri:https://google.com, 
                    type: User
            },
            userId: jmarthens1,
            businessPhone: null,
            salaryProrating: null,
            empId: 2023,
            lastModifiedDateTime: Date(1458308558000 + 0000),
            finalJobRole: null,
            username: jmarthens,
            married: false,
            futureLeader: null,
            salary: 79000.0,
            jobRole: Program Manager,
            Professional Services,
            nickname: null,
            salaryLocal: null
        }]
    }
}

Result:

empId-2023
lastModifiedDateTime-Date(1458308558000+0000)
salary-79000.0
userId-jmarthens1
jobRole-Program Manager, Professional Services
type-User
uri-https://google.com
username-jmarthens

Code:

package test;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

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

public class TestClass {
    private static StringBuilder strOut = new StringBuilder();

    public static void main(String[] args) {

        try {
            String json = "{\"d\" : {\"results\" : [{\"__metadata\" : {\"uri\" : \"https://apisalesdemo8.successfactors.com:443/odata/v2/User('jmarthens1')\","
                    + " \"type\" : \"SFOData.User\"}, \"userId\" : \"jmarthens1\", \"businessPhone\" : null, \"salaryProrating\" : null, \"empId\" : \"2023\", "
                    + "\"lastModifiedDateTime\" : \"Date(1458308558000+0000)\", \"finalJobRole\" : null, \"username\" : \"jmarthens\", \"married\" : false, "
                    + "\"futureLeader\" : null, \"salary\" : \"79000.0\", \"jobRole\" : \"Program Manager, Professional Services\", \"nickname\" : null, \"salaryLocal\" : null}]}}";
            JSONObject inputJson = new JSONObject(json);
            List<String> lst = new ArrayList<String>();
            lst = findKeysOfJsonObject(inputJson, lst);

            try (BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\temp\\temp.txt"))) {
                writer.write(strOut.toString());
            }
        } catch (JSONException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private static List<String> findKeysOfJsonArray(JSONArray jsonIn, List<String> keys) {
        List<String> keysFromArr = new ArrayList<>();

        if (jsonIn != null && jsonIn.length() != 0) {
            for (int i = 0; i < jsonIn.length(); i++) {
                JSONObject jsonObjIn = jsonIn.getJSONObject(i);
                keysFromArr = findKeysOfJsonObject(jsonObjIn, keys);
            }
        }

        return keysFromArr;
    }

    private static List<String> findKeysOfJsonObject(JSONObject jsonIn, List<String> keys) {

        Iterator<String> itr = jsonIn.keys();
        List<String> keysFromObj = makeList(itr);
        keys.addAll(keysFromObj);

        itr = jsonIn.keys();
        while (itr.hasNext()) {
            String itrStr = itr.next();
            // System.out.println("out " + itrStr);
            JSONObject jsout = null;
            JSONArray jsArr = null;
            if (jsonIn.get(itrStr).getClass() == JSONObject.class) {
                jsout = jsonIn.getJSONObject(itrStr);
                findKeysOfJsonObject(jsout, keys);
            } else if (jsonIn.get(itrStr).getClass() == JSONArray.class) {
                jsArr = jsonIn.getJSONArray(itrStr);
                keys.addAll(findKeysOfJsonArray(jsArr, keys));
            } else if (jsonIn.get(itrStr).getClass() == String.class) {
                System.out.println(itrStr + "-" + jsonIn.get(itrStr));
                strOut.append(itrStr + "," + jsonIn.get(itrStr));
                strOut.append(System.lineSeparator());
            }
        }
        return keys;
    }

    public static List<String> makeList(Iterator<String> iter) {
        List<String> list = new ArrayList<String>();
        while (iter.hasNext()) {
            list.add(iter.next());
        }
        return list;
    }
}
mattyman
  • 351
  • 2
  • 16
0
static Set<String> finalListOfKeys = new LinkedHashSet<String>();


public static void main(String[] args) {
    JSONParser parser = new JSONParser();

    try {

        Object obj = parser.parse(new FileReader("Absolute path of json file"));
        JSONObject jsonObject = (JSONObject) obj;
        Set<String> jsonKeys = jsonObject.keySet();
        for (String key : jsonKeys) {
            Object val = jsonObject.get(key);
            if (val instanceof JSONArray) {
                JSONArray array = (JSONArray) val;
                jsonArray(array, key);

            } else if (val instanceof JSONObject) {
                JSONObject jsonOb = (JSONObject) val;
                jsonObj(jsonOb, key);
            } else {
                finalListOfKeys.add(key);
                System.out.println("Key is : " + key);
            }
        }

        System.out.println("Final List : " + finalListOfKeys);

    } catch (Exception e) {
        e.printStackTrace();
    }
}


public static void jsonObj(JSONObject object, String key2) {
    Set<String> innerKeys = object.keySet();
    System.out.println("Inner Keys : " + innerKeys);
    for (String key : innerKeys) {
        System.out.println("Key : " + key);
        Object val = object.get(key);
        if (val instanceof JSONArray) {
            JSONArray array = (JSONArray) val;
            jsonArray(array, key2 + "->" + key);

        } else if (val instanceof JSONObject) {
            JSONObject jsonOb = (JSONObject) val;
            jsonObj(jsonOb, key2 + "->" + key);
        } else {
            finalListOfKeys.add(key2 + "->" + key);
            System.out.println("Key is : " + key2 + "->" + key);
        }
    }
}

public static void jsonArray(JSONArray array, String key) {
    if (array.size() == 0) {
        finalListOfKeys.add(key);
    } else {

        for (int i = 0; i < array.size(); i++) {
            Object jObject = array.get(i);
            if (jObject instanceof JSONObject) {
                JSONObject job = (JSONObject) jObject;
                System.out.println(job);
                jsonObj(job, key);

            }
        }
    }
}
  • 1
    You should really add some explanation as to why this should work - you can also add code as well as the comments in the code itself - in its current form, it does not provide any explanation which can help the rest of the community to understand what you did to solve/answer the question. This is especially important for an older question and the questions that already have answers. – Raymond Feb 03 '17 at 11:04
  • 1
    Thanks for the feedback.The code is pretty self-explanatory,hence I refrained from any comments. – Saptarshi Mitra Feb 03 '17 at 11:42