使用Gson反序列化JSON时引用父对象

编程入门 行业动态 更新时间:2024-10-28 17:30:17
本文介绍了使用Gson反序列化JSON时引用父对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给出以下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时引用父对象

本文发布于:2023-08-04 05:51:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1293522.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   序列化   Gson   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!