I am trying to deserialize a JSON array using GSON. All my nested objects are embedded in the inline object.
{ "Book": { "name": "Book 1", "published": 1999, "links": { "url": "www.book1.com" }, "embedded": { "Author": { "name": "John Doe", "links": { "url": "www.johndoe.com" } } } } }
I may also have this situation:
{ "Book": { "name": "Book 1", "published": 1999, "links": { "url": "www.book1.com" }, "embedded": { "Publisher": { "name": "Publishing Company", "links": { "url": "www.publishingcompany.com" } } } } }
This is a very simple example. Some of my objects can be nested in 2 or 3 levels, and all of them are in the "built-in" object. In addition, each object has a nested "url" inside the "links" object. I have about 20 different model objects, each with multiple fields, and each of them has a โbuilt-inโ object. I started writing custom deserializers for each model, but that seems to have missed the whole point of using gson, and I don't always know what an inline object is.
I found this answer , but it was for serializing objects. I tried to figure this out for a while and did not find anything that worked.
My book model is as follows:
public class Book { String name; int published; String url; Author author; Publisher publisher; }
Author class:
public class Author { String name; String url; }
Publisher Class:
public class Publisher { String name; String url; }
And here is my book deserializer so far:
public class BookDeserializer implements JsonDeserializer<Book> { @Override public Book deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { final JsonObject jsonObject = json.getAsJsonObject(); Book book = new Book(); book.setName(jsonObject.get("name").getAsString()); book.setPublished(jsonObject.get("published").getAsInt()); String url = jsonObject.getAsJsonObject("links").get("url").getAsString(); book.setUrl(url);
I still need to parse json and set each field for the book. Then I will need to add code to determine and use the correct deserializer for the nested object. It looks like I still need a special deserializer for each object to get the "url". I am new to gson, so maybe there is something that I am missing, but it seems that I could just manually parse all json and not even use gson. Maybe there is a way to smooth json?
Any ideas on how to parse this and still use the gson convenience, or is it even possible? Maybe Jackson can do it better?