1

I currently use json-simple library in Java to work with JSON objects. Most of the time I get JSON string from some external web service and need to parse and traverse it. Even for some not too complex JSON objects that might be pretty long typing exercise.

Let's assume I got following string as responseString:

{
  "employees": [
    {
      "firstName": "John",
      "lastName": "Doe"
    },
    {
      "firstName": "Anna",
      "lastName": "Smith"
    },
    {
      "firstName": "Peter",
      "lastName": "Jones"
    }
  ],
  "title": "some company",
  "headcount": 3
}

To get last name of 3d employee I'll have to:

JSONObject responseJson = (JSONObject) JSONValue.parse(responseString);
JSONArray employees = (JSONArray) responseJson.get("employees");
JSONObject firstEmployee = (JSONObject) employees.get(0);
String lastName = (String) firstEmployee.get("lastName");

Something like that at least. Not too long in this case, but might get complicated.

Is there any way for me (maybe switching to some other Java library?) to get more streamlined fluent approach working?

String lastName = JSONValue.parse(responseString).get("employees").get(0).get("lastName")

I can't think of any auto-casting approach here, so will appreciate any ideas.

Alex F
  • 273
  • 4
  • 13

1 Answers1

1

Try Groovy JsonSlurper

println new JsonSlurper().parseText(json).employees[0].lastName

Output:

Doe

But best solution is JsonPath - with typing

String name = JsonPath.parse(json).read("$.employees[0].lastName", String.class);
System.out.println(name);
Community
  • 1
  • 1
MariuszS
  • 30,646
  • 12
  • 114
  • 155