使用Gson反序列化JSON时引用父对象 [英] Reference parent object while deserializing a JSON using Gson

查看:309
本文介绍了使用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时引用父对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆