gpt4 book ai didi

java - 检查 jsonArray 是否为 null

转载 作者:行者123 更新时间:2023-12-02 02:47:45 24 4
gpt4 key购买 nike

我正在尝试检查 json 数组以获取作者姓名,如果为 null,我需要给我未知作者这个 json 数组

{  
"kind":"books#volumes",
"totalItems":604,
"items":[
{
"kind":"books#volume",
"id":"6tLAyQLSzG0C",
"etag":"wtUTTM0nDQA",
"selfLink":"https://www.googleapis.com/books/v1/volumes/6tLAyQLSzG0C",
"volumeInfo":{
"title":"Android for Work",
"subtitle":"Productivity for Professionals",
"authors":[
"Marziah Karch"
],

这是我的java代码

 // Create a JSONObject from the JSON response string
JSONObject root = new JSONObject(bookJSON);

// Extract the JSONArray
// which represents list of title of book ant author name.
JSONArray bookArray = root.getJSONArray("items");

for (int i = 0; i < bookArray.length(); i++) {

// Get a single booka t position i within the list of books
JSONObject currentBook = bookArray.getJSONObject(i);
JSONObject volumeInfo = currentBook.getJSONObject("volumeInfo");
// Extract the value for the key called " title"
String title="";
if(volumeInfo.has("title"))
{ title = volumeInfo.getString("title");}
JSONArray authors= volumeInfo.getJSONArray("authors");
String author = "";


for (int j = 0; j < authors.length(); j++) {
if(authors.length()==0){
// Convert the authors to a string
author = authors.getString(j);}else{author="unknown";}}

我可以获得书名,但作者姓名始终未知,我不知道为什么?

最佳答案

您的问题是在这种情况下if(authors.length()==0)

这应该是:

JSONArray authors= volumeInfo.getJSONArray("authors");
String author = null;
if(authors.length() > 0) {
author = authors.getString(authors.length() - 1);
} else {
author="unknown";
}

关于java - 检查 jsonArray 是否为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44339039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com