在这种情况下,我将实现一个自定义JsonDeserializer
为父对象,并传播Author
信息,像这样:
public class AuthorDeserializer implements JsonDeserializer<Author> {
@Override
public Author deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
final JsonObject authorObject = json.getAsJsonObject();
Author author = new Author();
author.name = authorObject.get("name").getAsString();
Type booksListType = new TypeToken<List<Book>>(){}.getType();
author.books = context.deserialize(authorObject.get("books"), booksListType);
for(Book book : author.books) {
book.author = author;
}
return author;
}
}
请注意,我的示例省略了错误检查。你会像这样使用它:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Author.class, new AuthorDeserializer())
.create();
为了展示它的工作原理,我只从示例 JSON 中提取了“authors”键,这样我就可以执行以下操作:
JsonElement authorsJson = new JsonParser().parse(json).getAsJsonObject().get("authors");
Type authorList = new TypeToken<List<Author>>(){}.getType();
List<Author> authors = gson.fromJson(authorsJson, authorList);
for(Author a : authors) {
System.out.println(a.name);
for(Book b : a.books) {
System.out.println("\t " + b.title + " by " + b.author.name);
}
}
其中打印:
Stephen King
Carrie by Stephen King
The Shining by Stephen King
Christine by Stephen King
Pet Sematary by Stephen King