我正在實現Android RESTful客戶端API。我想使用GSON將所有傳入的JSON響應解析到我的java模型中,然後使用Sugar ORM將所有數據緩存到數據庫以供脫機查看。如何使用GSON解析和緩存嵌套的JSON對象?
我有一個「作者」模型和一個「書」模型。理想情況下,你應該能夠通過這樣來解析和緩存的作者:
Author author = new Gson().fromJson(jsonObject, Author.class);
author.save(); // Saves the record to the db
然而,我的JSON結構要複雜得多,它不是東西,我可以改變。另外,這不會分離Book對象。例如,以下是將填充作者的ListView的JSON響應。嵌入作者是一系列的書籍。
{
"_links": {
"self": {
"href": "http://myapi.com/authors"
}
},
"_embedded": {
"authors": [
{
"id": 1,
"name": "John Doe",
"website": "http://johndoe.com",
"email": "[email protected]",
"bio": "Est rem et dolores illo est. Non quaerat aut. Id doloribus sed dicta exercitationem et. Perferendis aut necessitatibus debitis.\nEt earum est. Voluptatem minima suscipit blanditiis. Porro fugiat aliquam quia. Eum error et quibusdam dolores est architecto et.",
"likes_count": 4,
"_links": {
"self": {
"href": "http://myapi.com/authors/1"
}
},
"_embedded": {
"group": null,
"books": [
{
"id": 1,
"name": "Book 1",
"_links": {
"self": {
"href": "http://myapi.com/books/1"
}
}
}
]
}
},
{
"id": 2,
"name": "Jane Doe",
"website": "http://janedoe.com",
"email": "[email protected]",
"bio": "Excepturi dolorem laboriosam odio et quis itaque laudantium. Neque perspiciatis facere harum eligendi nemo veritatis ut. Qui occaecati facilis voluptatem ut consectetur placeat dolor. Veritatis quasi iste veniam aut. Expedita qui voluptate aut molestiae fuga quas itaque.\nVeritatis perspiciatis officiis quis dicta. Omnis voluptas possimus. Ut non rerum atque molestiae et consequatur aut. Quo molestiae animi aut nam voluptatem iusto.",
"likes_count": 10,
"_links": {
"self": {
"href": "http://myapi.com/authors/2"
}
},
"_embedded": {
"group": null,
"books": [
{
"id": 2,
"name": "A Book By Jane Doe",
"_links": {
"self": {
"href": "http://myapi.com/books/2"
}
}
},
{
"id": 3,
"name": "Another Book by Jane Doe",
"_links": {
"self": {
"href": "http://myapi.com/books/3"
}
}
}
]
}
}
]
}
}
這裏是我的作者模型:
public class Author extends SugarRecord<Author> {
@SerializedName("id")
private long authorId;
private String name;
private String website;
private String email;
private String bio;
@SerializedName("likes_count")
private int likesCount;
private String href;
...
}
這裏是我的書型號:
public class Book extends SugarRecord<Book> {
@SerializedName("id")
private long bookId;
private String name;
private String description;
private String publisher;
private int yearPublished;
private String rating;
@SerializedName("likes_count")
private int likesCount;
private String href;
...
}
現在,我只是通過作者的JSONArray迭代,並使用上面的代碼解析並緩存每個作者(「href」除外)。我的問題是,如何使用GSON將書籍解析爲他們自己的模型(不是作者模型的一部分)。 GSON甚至有可能嗎?
謝謝你的幫助,讓我知道如果我需要做出更清楚的事情!