Skip to content Skip to sidebar Skip to footer

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 fir

Solution 1:

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

publicclassMyModel {

    @ExposeprivateList<Place> places = newArrayList<Place>();

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

    /**
     *
     * @paramplaces
     * The places
     */publicvoidsetPlaces(List<Place> places) {
        this.places = places;
    }

}

publicclassPlace {

    @ExposeprivateString url;
    @ExposeprivateString name;
    @ExposeprivateString description;

    /**
     *
     * @return
     * The url
     */publicStringgetUrl() {
        return url;
    }

    /**
     *
     * @paramurl
     * The url
     */publicvoidsetUrl(String url) {
        this.url = url;
    }

    /**
     *
     * @return
     * The name
     */publicStringgetName() {
        return name;
    }

    /**
     *
     * @paramname
     * The name
     */publicvoidsetName(String name) {
        this.name = name;
    }

    /**
     *
     * @return
     * The description
     */publicStringgetDescription() {
        return description;
    }

    /**
     *
     * @paramdescription
     * The description
     */publicvoidsetDescription(String description) {
        this.description = description;
    }

}

Next create a restadapter like this:

publicclassSimpleRestClient {

private SimpleRestApi simpleRestApi;

publicSimpleRestClient() {

    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:

publicinterfaceSimpleRestApi {

@GET("Enter URL")publicvoidgetSimpleResponse(Callback<MyModel> handlerCallback);

}

Finally call it as follows:

simpleRestApi = newSimpleRestClient().getSimpleRestApi();
    simpleRestApi.getSimpleResponse(newCallback<MyModel>() {
        @Overridepublicvoidsuccess(MyModel responseHandler, Response response) {
            // here you can get your url, name and description.
        }

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

References:

jsonschema2pojo

A smart way to use retrofit

Post a Comment for "Retrofit: Problems Handling Array Or Single Object"