给出以下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对象具有对父"作者对象的引用?
Is there a way, using the Google Java library Gson, to deserialize the JSON and that the books objects has a reference to the "parent" author object?
是否可以不使用自定义解串器?
Is it possible without using a custom deserializer?
- 如果是:如何?
- 如果没有:使用自定义解串器是否仍然可以做到?
在这种情况下,我将为父对象实现自定义JsonDeserializer,并传播Author信息,如下所示:
In this case, I would implement a custom JsonDeserializer for the parent object, and propagate the Author info, like so:
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; } }请注意,我的示例省略了错误检查.您将像这样使用它:
Note that my example omits error checking. You would use it like so:
Gson gson = new GsonBuilder() .registerTypeAdapter(Author.class, new AuthorDeserializer()) .create();为了显示它的工作原理,我从示例JSON中仅提取了"authors"键,允许我执行以下操作:
To show it working, I pulled off just the "authors" key from your example JSON, allowing me to do this:
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更多推荐
使用Gson反序列化JSON时引用父对象
发布评论