英文:
Extract elements from JSONObject in Android
问题
我有一个名为object的JSONObject。
它包含了许多类为Books的对象。
这是第一个元素的打印输出:
I/System.out: {"id":"1","author":"Paula Hawkins","description":"每一天都一样\n\n瑞秋 她很快陷入了不仅调查中,还有所有相关人员的生活中。她做的比好的还多吗?","publication_date":"13\/01\/2015","title":"列车上的女孩","url_image":"hawkins.jpg"}
我想要获取id、作者等信息,但我不知道如何访问它。
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"); // 这将获得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();
}
这是我创建对象的代码。
有什么想法吗?
英文:
I have a JSONObject called object.
It has alot of objects of the class Books.
This is the print of the first element :
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"}
I would like to get the id, the author and such, but I don't know how to access it.
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();
}
This is the code on how I am creating the object.
Any ideas?
答案1
得分: 1
我明白了!
System.out.println(mainObject.getJSONObject(1).get("id"));
在这种情况下,您获取对象 1,然后使用 .get
获取所需获取的属性的名称。
无论如何,谢谢,希望这个答案对其他人有帮助!
英文:
I figured out!.
System.out.println(mainObject.getJSONObject(1).get("id"));
You get the object 1 in this case and .get the name of the attribute you want to get.
Thanks anyways and I hope this answers helps other people!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论