我正在实施Android RESTful客户端API。我想使用GSON将所有传入的JSON响应解析为我的java模型,然后使用Sugar ORM将所有数据缓存到数据库以供离线查看。
我有一个"作者"模特和"书"模型。理想情况下,您应该能够解析并缓存作者:
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": "john.doe@myapi.com",
"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": "jane.doe@myapi.com",
"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,并使用上面的代码来解析和缓存每个作者(&#34; href&#34;除外)。我的问题是,我如何使用GSON将Books解析为他们自己的模型(不是作者模型的一部分)。这对GSON来说是否可能?
感谢您的帮助,如果我需要更清楚的话,请告诉我们。
答案 0 :(得分:0)
是的,可以使用gson解析complexe json结构,你可以实现JsonDeserializer<T>
并根据需要解析你的json,如果你有一个非常大的json响应,它可能会让你遇到一些内存问题,在这种情况下它是更好地使用TypeAdapter<T>
这是一个很棒的教程,我希望它能帮到你gson-deserialiser-example