Let's assume we have the following two Java Classes (omitting the other class members):
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:
{"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.
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:
Try with GsonBuilder#setPrettyPrinting() that configures Gson to output Json that fits in a page for pretty printing. This option only affects Json serialization.
Read more about Gson that is typically used by first constructing a Gson instance and then invoking below method on it.
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
Sample code:
output:
JSON String to BookDetails Object
Here is the classes