0

I want to get the first "City" object from this JSON response from a URL (or get them all as an array and then use .map() operator in RxJava to get the first city):

{
    totalResultsCount: 5,
    names: [
        {
            city: stockholm
        },
        {
            city: oslo
        },
        {
            city: london
        },
        {
            city: moscow
        },
        {
            city: mumbai
        }
    ]
}

Here is code responsible for getting this:

public interface MyApi {

    @GET("searchJSON?")
    Observable<City[]> getPopulation(
        @QueryMap Map<String, String> queries
    );

}

and this class

public class MyApiService{

    private final String baseUrl = "myapiurl";
    private MyApi api;
    private final Gson gson;
    private final OkHttpClient okHttpClient;

    public MyApiService(){
        gson = new Gson();
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
        okHttpClient = new OkHttpClient();
        okHttpClient.newBuilder().addInterceptor(httpLoggingInterceptor);
        buildApi();
    }

    private void buildApi(){
        api = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
                .create(MyApi.class);
    }

    public Observable<City> getPopulation(String city) {
        return api
                .getPopulation(city)
                .map(c -> c[0])
                .subscribeOn(Schedulers.io());
    }
}

When I call getPopulation from an activity, I get this message:

D/Response: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

Here is how my City class looks like:

public class City {

    @SerializedName("city")
    private String name;

    public City(String name) {
        this.name = name;
    }
}

Any ideas?

EDIT:

I tried adding a custom deserializer like:

public class MyDeserializer implements JsonDeserializer<City> {

    @Override
    public City deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonElement cities = json.getAsJsonObject().get("names");
        return new Gson().fromJson(cities, City.class);
    }

}

and changing to:

gson = new GsonBuilder()
                .registerTypeAdapter(City.class, new MyDeserializer())
                .create();

but I still get the exact same response as earlier.

3
  • Delete my answer because it is Rx question I thougth the problem was JSON, try to add the relevant information using the wrapper class mentioned
    – cutiko
    Mar 8, 2019 at 12:07
  • @cutiko your answer was kinda helpful too. I managed to solve this by changing GET method and my getcities method and add some relevant RxJava methods. Thanks for your help.
    – CJR
    Mar 8, 2019 at 12:53
  • Welcomr, post the solution then
    – cutiko
    Mar 8, 2019 at 13:29

2 Answers 2

0

Your custom deserializer uses getAsJsonObject("names") but names is a JsonArray in your json response.

names: [] // This is a JsonArray

names: {} // This is a JsonObject
1
  • 1
    Any suggestions how i could parse to return city array from my get method?
    – CJR
    Mar 8, 2019 at 11:56
0

I manage to solve this.

I changed my API calls to:

@GET("searchJSON?")
    Observable<ResponseBody> getPopulation(
        @QueryMap Map<String, String> queries
    );

And I changed my api call method to:

public Observable<City> getPopulation(String city) {
        return api
                .getPopulation(city)
                .map(c -> c.getCities().get(0))
                .subscribeOn(Schedulers.io());

And I changed my Serializeble POJOs to:

public class ResponseBody implements Serializable
{

    @SerializedName("totalResultsCount")
    @Expose
    private int totalResultsCount;
    @SerializedName("names")
    @Expose
    private List<City> cities = null;

    public ResponseBody() {
    }

    public ResponseBody(int totalResultsCount, List<City> cities) {
        super();
        this.totalResultsCount = totalResultsCount;
        this.cities = cities;
    }

    public int getTotalResultsCount() {
        return totalResultsCount;
    }

    public void setTotalResultsCount(int totalResultsCount) {
        this.totalResultsCount = totalResultsCount;
    }

    public List<City> getCities() {
        return cities;
    }

    public void setNames(List<City> cities) {
        this.cities = cities;
    }

}

and

public class City implements Serializable
{
    @SerializedName("name")
    @Expose
    private String name;

    public City() {
    }

    public City(String name) {
        super();
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

And I complete removed the custom Deserializer.

It was a combination of my POJO and Wrong choice of RxJava operations which led to my problem. I hope this answer might help someone in the future.

If anyone have a better solution/way to handle this I would appreciate comments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.