我正在尝试从 Github Sample Collection of Books 中提取数据但我得到一个空白屏幕。这是我的 JSON 解析代码。
try {
JSONObject bookObject = new JSONObject(SAMPLE);
JSONArray booksArray = bookObject.getJSONArray("books");
for (int i = 0; i < booksArray.length(); i++){
JSONObject currentBook = booksArray.getJSONObject(i);
String title = currentBook.getString("title");
String author = currentBook.getString("author");
String isbn = currentBook.getString("isbn");
Book book = new Book(title,author,isbn);
books.add(book);
}
}catch (JSONException e){
Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
}
最佳答案
我向你推荐使用 GSON,这是一个非常简单的库
到Json
Gson gson = new Gson();
Staff obj = new Staff();
// 1. Java object to JSON file
gson.toJson(obj, new FileWriter("C:\\projects\\staff.json"));
// 2. Java object to JSON string
String jsonInString = gson.toJson(obj);
来自 Json
Gson gson = new Gson();
// 1. JSON file to Java object
Staff staff = gson.fromJson(new FileReader("C:\\projects\\staff.json"), Staff.class);
// 2. JSON string to Java object
String json = "{'name' : 'mkyong'}";
Staff staff = gson.fromJson(json, Staff.class);
// 3. JSON file to JsonElement, later String
JsonElement json = gson.fromJson(new FileReader("C:\\projects\\staff.json"), JsonElement.class);
String result = gson.toJson(json);
如果您想查看更多相关信息,可以查看此链接:https://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
关于java - 从 JSON 字符串 android 中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57199593/