'Simplifying POJO to be used by Gson

I have a JSON with the following part:

{
  "authors": [
    {
      "author": {
        "name": "Foo Bar"
      }
    },
    {
      "author": {
        "name": "Bar Foo"
      }
    }
  ]
}

It can easilby be mapped to the following DTO:

public class Response {

    @SerializedName("authors")
    private List<AuthorsItem> authors;
}

class AuthorsItem {

    @SerializedName("author")
    private Author author;
}

class Author {

    @SerializedName("name")
    private String name;
}

getters/setters omitted for brevity

Is there a way to avoid such a complicated structure and have e.g. List<Author> authors? It can be done by writing a class implementing JsonDeserializer but this is quite verbose.



Solution 1:[1]

If I understand you correctly, you can only define the Author class and just have the List from where you are accessing the data right? (Maybe as a method in a controller class)

Example: void saveAuthors(List<Author> authors) {}

class Author {

    @SerializedName("name")
    private String name;
}

Then your JSON would have to be structured as follows.

[
  {
     "name": "Foo Bar"
  },
  {
     "name": "Bar Foo"
  }
]

When deserializing, you can do the deserialization in a way that it identifies the list correctly.

You can refer to this tutorial for more info: How to Serialize Deserialize List of Objects in Java? Java Serialization Example

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dilini Peiris