Reputation: 57
I'm trying to extract data from Github Sample Collection of Books but i am getting a blank screen. here is my JSON parsing code.
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);
}
Upvotes: 2
Views: 2456
Reputation: 47
Try this :
Gson gson = new Gson();
JSONObject o = new JSONObject(jsonData.toString()); // pass your data here
JSONArray arr = new JSONArray(o.get("books").toString());
List<Book> books = new ArrayList<Book>();
for (int i = 0; i < arr.length(); i++) {
Book book = gson.fromJson(arr.get(i).toString(), Book.class);
books.add(book);
}
I have used Gson library here. There are other libraries as well. Refer this link for more details: http://tutorials.jenkov.com/java-json/gson-jsonparser.html
Upvotes: 2
Reputation: 228
you need to convert the response from the network service to string and then get the jsonArray it will work
Like this ::
@Override
public void onResponse(Call call, final okhttp3.Response response) throws IOException {
final String stringResponse = response.body().string();
//insted of sample pass the stringresponse it will work
JSONObject bookObject = new JSONObject(stringResponse);
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);
}
});
Upvotes: 1
Reputation: 5282
I recommend to you use GSON, is very easy library
To 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);
From 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);
If you want to see more information about this you can check this link: https://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
Upvotes: 4