JSON { public static String evaluate(String jsonpath, Object data) { String json = serialize(data); if (jsonpath == null || jsonpath.trim().isEmpty()) { return json; } if (json != null) { Object result = JsonPath.parse(json).read(jsonpath); if (result != null) { if (result.getClass() == JSONArray.class) { JSONArray arr=(JSONArray)result; if (arr.isEmpty()) { result = null; } else if (arr.size() == 1) { result = arr.get(0); } } return serialize(result); } } return null; }  static String serialize(Object data); static boolean predicate(String jsonpath, Object data); static String evaluate(String jsonpath, Object data);  }
@Test public void testEvaluateStringToField() { String json = "{ \"orderId\": \"1\" }"; String expr = "$.orderId"; String result = JSON.evaluate(expr, json); assertNotNull(result); assertEquals("1", result); }
@Test public void testEvaluateStringToElement() { String json = "{ \"order\": { \"orderId\": \"1\" } }"; String expr = "$.order"; String result = JSON.evaluate(expr, json); assertNotNull(result); assertEquals("{\"orderId\":\"1\"}", result); }
@Test public void testEvaluateObjectToField() { Order order = new Order(); order.setOrderId("1"); String expr = "$.orderId"; String result = JSON.evaluate(expr, order); assertNotNull(result); assertEquals("1", result); }
@Test public void testEvaluateNavigation() { String show = "The Lion King"; String json = "{ \"performance\": { \"name\": \"" + show + "\" }}"; String expression = "$.performance.name"; String result = JSON.evaluate(expression, json.getBytes()); assertNotNull(result); assertEquals(show, result); }
@Test public void testEvaluateFunctionLength() { String expected = "2"; String json = "{\"id\":1,\"tickets\":[{\"id\":1,\"seat\":{\"rowNumber\":1,\"number\":2," + "\"section\":{\"id\":1,\"name\":\"A\",\"description\":\"Premier platinum reserve\"," + "\"numberOfRows\":20,\"rowCapacity\":100,\"capacity\":2000}},\"ticketCategory\":" + "{\"id\":1,\"description\":\"Adult\"},\"price\":219.5},{\"id\":2,\"seat\":" + "{\"rowNumber\":1,\"number\":1,\"section\":{\"id\":1,\"name\":\"A\",\"description\":" + "\"Premier platinum reserve\",\"numberOfRows\":20,\"rowCapacity\":100,\"capacity\":2000}}," + "\"ticketCategory\":{\"id\":1,\"description\":\"Adult\"},\"price\":219.5}],\"performance\":" + "{\"id\":1,\"date\":1442858400000},\"cancellationCode\":\"abc\",\"createdOn\":1463756307069," + "\"contactEmail\":\"gbrown@redhat.com\",\"totalTicketPrice\":439.0}"; String expression = "$.tickets.length()"; String result = JSON.evaluate(expression, json.getBytes()); assertNotNull(result); assertEquals(expected, result); }