2016-11-28 527 views
0

我想使用com.jayway.jsonpath.JsonPath从JSON字符串读取键/值:com.jayway.jsonpath.JsonPath找不到钥匙

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

但我得到的错误:

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'. 

印刷contentAsString给出:

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

contentAsString无效的JSON?

回答

1

您发布团块不是有效JSON对象,然而,这是一个有效的JSON阵列

要阅读此使用JsonPath,尝试使用此:

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

这将得到key对象的值,从初始阵列的第0个元素。