Search code examples
javaadapterstrategy-pattern

REST client using both Simple XML and Gson libraries: Use common POJOs or adapter pattern?


In my java app (specifically, Android app), I make a REST call (GET). The response could be either XML or JSON. I use a Strategy Pattern which decides what parser to employ based on the Content Type of the response.

If the response is XML, I use Simple library to parse the response into my POJOs, and if the response is JSON, I use Gson library.

Now my question: Is there any benefit in having a single POJO which containing both Simple and Gson annotations? Or, is it better to separate out the 2 POJOs and then have an Adapter (or maybe Wrapper) to "convert" to a generic POJO? In other words, what are the pros and cons of the following approaches?

Approach 1:

class PojoCommon {

    @SimpleXmlAnnotations
    @GsonAnnotations
    private int age;

    @SimpleXmlAnnotations
    @GsonAnnotations
    private String name;

    //Constructors, Getters and Setters ...
}

Approach 2:

class Pojo{

    private int age;
    private String name;
}

class PojoXml{
    @SimpleXmlAnnotations
    private int age;

    @SimpleXmlAnnotations
    private String name;

    public Pojo toGenericPojo(){
        return new Pojo(this.age, this.name);
    }
}

class PojoJson{

    @GsonAnnotations
    private int age;

    @GsonAnnotations
    private String name;

    public Pojo toGenericPojo(){
        return new Pojo(this.age, this.name);
    }
}

Solution

  • Though Approach1 is better in term of maintenance but you already have answered your question as in long term with any proposed changes it can make things complex.

    My Suggestion is to go for second one create POJO for each individual type and use a wrapper/adapter approach for the conversion