给出以下JSON:
{
"authors": [{
"name": "Stephen King",
"books": [{
"title": "Carrie"
}, {
"title": "The Shining"
}, {
"title": "Christine"
}, {
"title": "Pet Sematary"
}]
}]
}
这个对象结构:
public class Author {
private List<Book> books;
private String name;
}
public class Book {
private transient Author author;
private String title;
}
是否有办法使用Google Java库Gson反序列化JSON,并且books对象引用了#34; parent&#34;作者对象?
是否可以不使用使用自定义反序列化程序?
答案 0 :(得分:6)
在这种情况下,我会为父对象实现自定义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();
为了展示它的工作原理,我只选择了#34;作者&#34;来自您的示例JSON的密钥,允许我这样做:
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