0

I have a json object as below.

{
    "products": [
        {
            "details": {
                "name": "xxx",
                "price": "100rs"
            },
            "description": "Buy this product"

        }, {
            "details": [{
                "name": "yyy",
                "price": "200rs"
            }],
            "description": "another project"
        }
    ]
}

Here the details are presented in 2 formats. How can I create a POJO (Plain Old Java Object) class of this to use for the Retrofit api?

Simon Kirsten
  • 2,542
  • 18
  • 21
Krishna
  • 805
  • 8
  • 14
  • 2
    Not a Java expert, but I guess you can't have two fields with the same name in one class. One should be "detail" and the other "details", at least. – Raphaël Althaus Jun 13 '16 at 16:36
  • Use this online tool, hope that will help you.. http://pojo.sodhanalibrary.com/ – D_Alpha Jun 13 '16 at 17:16
  • I think you can write a custom deserializer like this guy: http://stackoverflow.com/questions/35502079/custom-converter-for-retrofit-2 – nasch Jun 13 '16 at 17:27

1 Answers1

0

I think that's bad api response and should be fixed from backend. But if you want to address the problem, you have to deserialize response to String using String converter. You can't do deserialize it to your Pojo using Gson converter.

StringConverter.java

public class StringConverter implements Converter {

    @Override
    public Object fromBody(TypedInput typedInput, Type type) throws ConversionException {
        String text = null;
        try {
            text = fromStream(typedInput.in());
        } catch (IOException ignored) {  }

        return text;
    }

    @Override
    public TypedOutput toBody(Object o) {
        return null;
    }

    public static String fromStream(InputStream in) throws IOException     {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder out = new StringBuilder();
        String newLine = System.getProperty("line.separator");
        String line;
        while ((line = reader.readLine()) != null) {
            out.append(line);
            out.append(newLine);
        }
        return out.toString();
    } 
}

API Call implementation

RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint(API_URL) 
            .setConverter(new StringConverter())
            .build();

YourAPI api = restAdapter.create(YourAPI.class);
api.yourService(parameter,new RestCallback<String>() { 

    @Override
    public void success(String response, Response retrofitResponse) {
        super.success(response, retrofitResponse);
        //process your response here
        //convert it from string to your POJO, JSON Object, or JSONArray manually

    }

    @Override
    public void failure(RetrofitError error) { 
       super.failure(error);
    }

});
ikhsanudinhakim
  • 1,554
  • 16
  • 23