我正在尝试读取Java中JSON数组的内容,并将每个元素作为JSON字符串获取。我的尝试失败了。
我们假设这里是基本的JSON:
{ "book": [
{ "category": "",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": ""
},
{ "category": "fiction",
"author": "",
"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
}
]
}
然后遍历整个数组,并且需要将每个元素都作为JSON字符串获取(某些属性可以为空)。所以第一个字符串是:
{ "category": "",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": ""
}
这是我做的:
String response = Unirest.get(db).header("cache-control", "no-cache").asString().getBody();
int length = JsonPath.read(response, "$.book.length()");
System.out.println(length);
for (int i = 0; i < length; i++) {
String json = JsonPath.read(response, "$.book["+i+"]").toString();
System.out.println("1111111\n"+json);
process(json);
}
但是我得到的是混乱的,并且不是相同的字符串。它不包含""
。
解决方案是什么?
答案 0 :(得分:1)
正如我在评论中提到的,JsonPath将读取一个JSON对象并像这样返回它。它就像一个HashMap,其类型由解析的内容定义。如前所述,如果您希望在提取值后将其作为Json值,则需要再次将读取的内容转换回Json:
public static void main(String[] args) {
String response = "{ \"book\": [ " +
" { \"category\": \"\"," +
" \"author\": \"Nigel Rees\"," +
" \"title\": \"Sayings of the Century\"," +
" \"price\": \"\"" +
" }," +
" { \"category\": \"fiction\"," +
" \"author\": \"\"," +
" \"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" +
" }" +
" ]" +
"}";
int length = JsonPath.read(response, "$.book.length()");
System.out.println(length);
Configuration conf = Configuration.defaultConfiguration();
Object document = Configuration.defaultConfiguration().jsonProvider().parse(response);
for (int i = 0; i < length; i++) {
String json = conf.jsonProvider().toJson(JsonPath.read(document, "$.book["+i+"]"));
System.out.println(json);
//process(json);
}
}
这将输出:
{"category":"","author":"Nigel Rees","title":"Sayings of the Century","price":""}
{"category":"fiction","author":"","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}
我刚刚在Docs中了解到它,使用Configuration解析json将使您的代码仅解析一次。甚至可以进行改进(删除int length
东西),但我会留给您:)