0

Trying to read Json Message like below

{
  "employees": [
    {
      "firstName": "John",
      "lastName": "Doe"
    },
    {
      "firstName": "Anna",
      "lastName": "Smith"
    },
    {
      "firstName": "Peter",
      "lastName": "Jones"
    }
  ]
}

I want to read all keynames like employees,firstName,lastName etc.. in java. in XML we do this while parsing we specify * in dom object and get all node names, how to do this in java?

Syam S
  • 8,421
  • 1
  • 26
  • 36
khuddus
  • 11
  • 1
  • 3

2 Answers2

1

Use org.json library.

Example:

import org.json.*;

String myJSONString =  // put here your json object
JSONObject object = new JSONObject(myJSONString);
// get all the keys
String[] keys = JSONObject.getNames(object);

// iterate over them
for (String key : keys)
{
    // retrieve the values
    Object value = object.get(key);
    // if you just have strings:
    String value = (String) object.get(key);

}

JAR: http://mvnrepository.com/artifact/org.json/json

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
  • Getting below error when using the code "The method getNames(JSONObject) is undefined for the type JSONObject" – khuddus Aug 27 '15 at 16:21
0

This didnt seems to work anymore. However, Rickey pointed out another solution using iterators, which is mostly a smarter idea to use anyways:

JSONObject jsonObject = new JSONObject(contents.trim());
Iterator<String> keys = jsonObject.keys();

while(keys.hasNext()) {
    String key = keys.next();
    if (jsonObject.get(key) instanceof JSONObject) {
          // do something with jsonObject here      
    }
}

(Copied from here)

Mirco
  • 23
  • 1
  • 7