我有以下 json 数据:-
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}
断言 json 的方法:-
public void assertJsonvalue (String description, String jsonString,
String path, Object expectedValue) {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> jsonMap = null;
try {
jsonMap = objectMapper.readValue(jsonString,
new TypeReference<Map<String, Object>>() {
});
} catch (IOException e) {
fail("Could not parse json from string:" + jsonString);
}
Object actualValue = null;
try {
actualValue = PropertyUtils.getProperty(jsonMap, path);
System.out.println("actualValue" + actualValue);
} catch (IllegalAccessException e) {
// error here
}
assertEquals(description, expectedValue, actualValue);
}
当我尝试使用以下方法获取 json 值时,它运行良好。
assertJsonValue("bicycle color", json, "store.bicycle.color", "red");
我想从 json 中获取数组值,例如第一本书的详细信息。
我尝试了以下方法,但这对我没有帮助。
json路径如下:-
- “store.book[0]”
- “store.book.[0]”
- “store.book.category”
我怎样才能做到这一点 ?