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?

2
  • Which parser are you using? Commented Aug 27, 2015 at 16:11
  • 1
    possible duplicate of How to parse JSON in Java Commented Aug 27, 2015 at 16:16

2 Answers 2

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

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

1 Comment

Getting below error when using the code "The method getNames(JSONObject) is undefined for the type JSONObject"
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)

Comments

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.