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

时间:2014-05-28 18:50:59

标签: java json gson

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

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

class Author {
    private String name;
}

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

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

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

2 个答案:

答案 0 :(得分:6)

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

阅读有关Gson的更多信息,通常首先构建一个Gson实例,然后在其上调用下面的方法。


BookDetails对象到JSON字符串

示例代码:

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);

输出:

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

JST字符串到BookDetails对象

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

这是课程

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
}

答案 1 :(得分:6)

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

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;
       }
    }
}