使用 gson 将嵌套的 Java 对象转换为 json 或从 json 转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23919605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 09:02:08  来源:igfitidea点击:

Translating nested Java objects to/from json using gson

javajsongson

提问by shahins

Let's assume we have the following two Java Classes (omitting the other class members):

假设我们有以下两个 Java 类(省略其他类成员):

class Book {
    private String name;
    private String[] tags;
    private int price;
    private Author author;
}

class Author {
    private String name;
}

Furthermore, assume we have the following json object:

此外,假设我们有以下 json 对象:

{"Book": {
    "name": "Bible",
    "price": 20,
    "tags": ["God", "Religion"],
    "writer": {
        "name": "Jesus"
    }
}

I am trying to find the best way to convert a Java Book instance to json and back using gson. To make the example more interesting, note that in json, I want to use "writer" instead of "Author". Can you please help? Ideally, I would like to see a complete implementation.

我正在尝试找到使用 gson 将 Java Book 实例转换为 json 并返回的最佳方法。为了使示例更有趣,请注意在 json 中,我想使用“writer”而不是“Author”。你能帮忙吗?理想情况下,我希望看到一个完整的实现。

采纳答案by shahins

Thanks for all the answers. I was able to figure it out and implement it using some custom serializer and deserializer. Here is my own solution:

感谢所有的答案。我能够弄清楚并使用一些自定义序列化器和反序列化器实现它。这是我自己的解决方案:

public class JsonTranslator {
    private static Gson gson = null;

    public void test(Book book1) {
        JsonElement je = gson.toJson(book1);  // convert book1 to json
        Book book2 = gson.fromJson(je, Book.class); // convert json to book2
        // book1 and book2 should be equivalent
    }

    public JsonTranslator() {

        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(Book.class, new BookTrnaslator());
        builder.registerTypeAdapter(Author.class, new AuthorTrnaslator());
        builder.setPrettyPrinting();
        gson = builder.create();
    }


    private class BookTrnaslator implements JsonDeserializer<Book>, JsonSerializer<Book> {
        public Card deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            JsonObject jobj = json.getAsJsonObject();
            Book book = new Book();
            book.setName(jobj.get("name").getAsString());
            book.setTags(jobj.get("tags").getAsJsonArray()); //Assuming setTags(JsonArray ja) exists
            book.setName(jobj.get("price").getAsInt());
            book.setAuthor(gson.fromJson(jobj.get("writer"), Author.class));
            return book;
        }

       public JsonElement serialize(Book src, Type typeOfSrc, JsonSerializationContext context) {
            JsonObject jobj = new JsonObject();
            jobj.addProperty("name", src.getName());
            jobj.add("tags", src.getTagsAsJsonArray());
            jobj.addProperty("price", src.getPrice());
            jobj.add("writer", gson.toJson(src.getAuthor()));
            return jobj;
       }
    }

    private class AuthorTrnaslator implements JsonDeserializer<Author>, JsonSerializer<Author> {
        public Card deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            JsonObject jobj = json.getAsJsonObject();
            Author author = new Author();
            author.setName(jobj.get("name").getAsString());
            return author;
        }

       public JsonElement serialize(Author src, Type typeOfSrc, JsonSerializationContext context) {
            JsonObject jobj = new JsonObject();
            jobj.addProperty("name", src.getName());
            return jobj;
       }
    }
}

回答by Braj

Try with GsonBuilder#setPrettyPrinting()that configures Gson to output Json that fits in a page for pretty printing. This option only affects Json serialization.

尝试使用GsonBuilder#setPrettyPrinting()将 Gson 配置为输出适合页面的 Json 以进行漂亮的打印。此选项仅影响 Json 序列化。

Read more about Gsonthat is typically used by first constructing a Gson instance and then invoking below method on it.

阅读有关Gson 的更多信息,通常通过首先构造 Gson 实例然后在其上调用以下方法来使用它。

  • toJson(Object)that serializes the specified object into its equivalent Json representation.

  • fromJson(String, Class)that deserializes the specified Json into an object of the specified class.



BookDetails Object to JSON String

BookDetails 对象到 JSON 字符串

Sample code:

示例代码:

Book book = new Book();
book.setName("Bible");
book.setTags(new String[] { "God", "Religion" });
book.setPrice(20);
Author author = new Author();
author.setName("Jesus");
book.setWriter(author);

BookDetails bookDetails = new BookDetails();
bookDetails.setBook(book);

String jsonString = new Gson().toJson(bookDetails);
// JOSN with pretty printing
// String jsonString = new GsonBuilder().setPrettyPrinting().create().toJson(bookDetails);
System.out.println(jsonString);

output:

输出:

{"Book":{"name":"Bible","tags":["God","Religion"],"price":20,"writer":{"name":"Jesus"}}}

JSON String to BookDetails Object

JSON 字符串到 BookDetails 对象

BookDetails newBookDetails = new Gson().fromJson(jsonString, BookDetails.class);


Here is the classes

这是课程

class BookDetails {
    private Book Book;
    // getter & setter
}

class Book {
    private String name;
    private String[] tags;
    private int price;
    // Variable name should be writer instead of author as mapped to JSON string
    private Author writer; 
    // getter & setter
}

class Author {
    private String name;
    // getter & setter
}