u123 u123 - 12 days ago 5
JSON Question

com.jayway.jsonpath.JsonPath cannot find key

I am trying to use com.jayway.jsonpath.JsonPath to read key/values from a JSON string:

String contentAsString = mvcResult.getResponse().getContentAsString();
System.out.println(contentAsString);
Object value = JsonPath.read(contentAsString, "$.key");


But I get the error:

Expected to find an object with property ['key'] in path $ but found 'net.minidev.json.JSONArray'. This is not a json object according to the JsonProvider: 'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider'.


Printing
contentAsString
gives:

[{"firstName":"N","key":"mykey"}]


Is
contentAsString
not valid JSON?

Answer

The blob that you posted is not a valid JSON Object, however, it IS a valid JSON Array.

To read this using JsonPath, try using this:

Object value = JsonPath.read(contentAsString, "$[0].key");

This will get the value of the key object, from the 0th element of the initial array.