gson 从Android中的JSONObject提取元素

2nbm6dog  于 2022-11-23  发布在  Android
关注(0)|答案(1)|浏览(194)

我有一个名为JSONObject的对象。
它有很多图书类的对象。
这是第一个元素的打印:

I/System.out: {"id":"1","author":"Paula Hawkins","description":"EVERY DAY THE SAME\n\nRachel   Soon she is deeply entangled not only in the investigation but in the lives of everyone involved. Has she done more harm than good?","publication_date":"13\/01\/2015","title":"The girl on the train","url_image":"hawkins.jpg"}

我想得到的身份证,作者等,但我不知道如何访问它。

Gson gson = new Gson();
JSONArray mainObject = new JSONArray(total.toString());
for (int i = 0; i < mainObject.length(); i++) {
    JSONObject object = mainObject.getJSONObject(i);
    int id = object.getInt("id");  //This will have the value of the id
    String author = object.getString("author");
    String description = object.getString("description");
    String publication_date = object.getString("publication_date");
    String title = object.getString("title");
    String url_image = object.getString("url_image");

}
System.out.println(mainObject.get(1));

for(int i =0; i<mainObject.length(); i++){
    book = new Book();
}

这是我如何创建对象的代码。
有什么想法吗?

jljoyd4f

jljoyd4f1#

我想通了!

System.out.println(mainObject.getJSONObject(1).get("id"));

在本例中,您获取对象1,并.get要获取的属性的名称。
无论如何,谢谢你,我希望这个答案能帮助其他人!

相关问题