Ersen Osman
Ersen Osman

Reputation: 7247

Retrofit: Problems handling array or single object

I have been following other answers but there is a missing step that i cant find which is resulting in call being successful but the data not being parsed correctly because the first call i make returns a list of objects but only 1 object is returned which is all null

MyModel.java

    public class MyModel {
        @SerializedName("url")
        private String mUrl;

        @SerializedName("name")
        private String mName;

        @SerializedName("description")
        private String mDescription;
    }

MyModelDeserializer.java

This just checks if its array or object and will simply return the array

public class MyModelTypeAdapter implements JsonDeserializer<ArrayList<MyModel>>{

    @Override
    public ArrayList<MyModel> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            ArrayList<MyModel> objects = new ArrayList<>();
            if(json.isJsonArray()){
                for(JsonElement e : json.getAsJsonArray()){
                    objects.add((MyModel)context.deserialize(e,MyModel.class));
                }
            }else if(json.isJsonObject()){
                objects.add((MyModel)context.deserialize(json,MyModel.class));
            }
        return objects;
    }
}

Some other stuff

 Gson gson = new GsonBuilder()
                    .registerTypeAdapter(new TypeToken<ArrayList<MyModel>>() {}.getType(), new MyModelTypeAdapter())
                    .create();
 restAdapter = new RestAdapter.Builder()
                    .setEndpoint(BuildConstants.BASE_URL)
                    .setConverter(new GsonConverter(gson))
                    .setClient(new OkClient(okHttpClient))
                    .setLogLevel(RestAdapter.LogLevel.FULL)
                    .build();

This is the part which confusing me, what do i put as the return type of the callback

@GET(URLConstants.LIST_URL)
    void getData(Callback<ArrayList<MyModel>> callback);

Edit JSON data

{
  "places": [
    {
      "url": "www.google.com",
      "name": "Google",
      "description": "Search engine"
    },
    {
      "url": "www.Facebook.com",
      "name": "Facebook",
      "description": "Social Network"
    },

    {
      "url": "www.amazon.com",
      "name": "Amazon",
      "description": "Shopping"
    }
]
  }

Upvotes: 1

Views: 1453

Answers (1)

Srijith
Srijith

Reputation: 1715

First create a POJO class to handle json. You can use jsonschema2pojo to create pojo class for your json:

public class MyModel {

    @Expose
    private List<Place> places = new ArrayList<Place>();

    /**
     *
     * @return
     * The places
     */
    public List<Place> getPlaces() {
        return places;
    }

    /**
     *
     * @param places
     * The places
     */
    public void setPlaces(List<Place> places) {
        this.places = places;
    }

}

public class Place {

    @Expose
    private String url;
    @Expose
    private String name;
    @Expose
    private String description;

    /**
     *
     * @return
     * The url
     */
    public String getUrl() {
        return url;
    }

    /**
     *
     * @param url
     * The url
     */
    public void setUrl(String url) {
        this.url = url;
    }

    /**
     *
     * @return
     * The name
     */
    public String getName() {
        return name;
    }

    /**
     *
     * @param name
     * The name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     *
     * @return
     * The description
     */
    public String getDescription() {
        return description;
    }

    /**
     *
     * @param description
     * The description
     */
    public void setDescription(String description) {
        this.description = description;
    }

}

Next create a restadapter like this:

public class SimpleRestClient {

private SimpleRestApi simpleRestApi;

public SimpleRestClient() {

    RestAdapter restAdapter = new RestAdapter.Builder()
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .setEndpoint(Constants.BASE_URL)
            .build();

    simpleRestApi = restAdapter.create(SimpleRestApi.class);

}

public SimpleRestApi getSimpleRestApi() {

    return simpleRestApi;

}

}

Now to create the api interface. Here we are setting our POJO class to handle the json response:

public interface SimpleRestApi {

@GET("Enter URL")
public void getSimpleResponse(Callback<MyModel> handlerCallback);

}

Finally call it as follows:

simpleRestApi = new SimpleRestClient().getSimpleRestApi();
    simpleRestApi.getSimpleResponse(new Callback<MyModel>() {
        @Override
        public void success(MyModel responseHandler, Response response) {
            // here you can get your url, name and description.
        }

        @Override
        public void failure(RetrofitError error) {
            progress.dismiss();
            Log.e("CLASS", "JSON: " + error.getCause());
        }
    });

References:

jsonschema2pojo

A smart way to use retrofit

Upvotes: 1

Related Questions