2016-11-28 533 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個元素。