gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:42:03 26 4
gpt4 key购买 nike

给定以下 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 并且书籍对象具有对“父”作者对象的引用?

是否有可能使用自定义解串器?

  • 如果是:如何?
  • 如果否:是否仍然可以使用自定义反序列化器来完成?

最佳答案

在这种情况下,我将为父对象实现自定义 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 中提取了“作者”键,允许我这样做:

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

关于java - 使用 Gson 反序列化 JSON 时引用父对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34901411/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com