我正在尝试使用 com.jayway.jsonpath.JsonPath 从 JSON 字符串读取键/值:
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 吗?
最佳答案
您发布的 blob不是有效的 JSON 对象,但是,它是有效的 JSON 数组。
要使用 JsonPath 阅读此内容,请尝试使用以下内容:
Object value = JsonPath.read(contentAsString, "$[0].key");
这将从初始数组的第 0 个元素获取 key
对象的值。
关于json - com.jayway.jsonpath.JsonPath 找不到 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40853263/