playframework Java - Working with JSON Transversing a JSON document


Example

In the following examples, json contains a JSON object with the following data:

[
  {
    "name": "John Doe",
    "work": {
      "company": {
        "name": "ASDF INC",
        "country": "USA"
      },
      "cargo": "Programmer"
    },
    "tags": ["java", "jvm", "play"]
  },
  {
    "name": "Bob Doe",
    "work": {
      "company": {
        "name": "NOPE INC",
        "country": "AUSTRALIA"
      },
      "cargo": "SysAdmin"
    },
    "tags": ["puppet", "ssh", "networking"],
    "active": true
  }
]

Get the name of some user (unsafe)

JsonNode node = json.get(0).get("name"); // --> "John Doe"
// This will throw a NullPointerException, because there is only two elements
JsonNode node = json.get(2).get("name"); // --> *crash*

Get the user name (safe way)

JsonNode node1 = json.at("/0/name"); // --> TextNode("John Doe")
JsonNode node2 = json.at("/2/name"); // --> MissingNode instance
if (! node2.isMissingNode()) {
    String name = node2.asText();    
}

Get the country where first user works

JsonNode node2 = json.at("/0/work/company/country"); // TextNode("USA")

Get every countries

List<JsonNode> d = json.findValues("country"); // List(TextNode("USA"), TextNode("AUSTRALIA"))

Find every user that contains the attribute "active"

List<JsonNode> e = json.findParents("active"); // List(ObjectNode("Bob Doe"))