2

I have to make a get request from a server which gives me a lot of information. From what I found searching it seems like I can do this only with model classes. Thing is that to cover all the response the server sends to me I have to make 53 model classes in which to store the information.

I was wondering if there is a simpler method, like to store the information in a JSON or something.

I am using Retrofit with OKHttp.

getTimeSessionsCall.enqueue(new Callback<JSONObject>() {
        @Override
        public void onResponse(Call<JSONObject> call, Response<JSONObject> response) {

            Log.i("getTimeSessions",Integer.toString(response.code()));

        }

        @Override
        public void onFailure(Call<JSONObject> call, Throwable t) {

        }
    });

I tried this kind of call and it stores nothing. The code is 200, but the JSON remains empty.

Thank you in advance!

Boanta Ionut
  • 402
  • 8
  • 24
  • Consider using GSON's JsonObject instead - it maps easily by GsonConverterFactory already available in Retrofit 2 - you can set Call as the result of your API interface call. – Boris Treukhov Oct 26 '17 at 15:03

2 Answers2

6

The reason JSONObject is null is because Retrofit doesn't know how to parse your response. What you can do is get the response as a string and then construct a JsonObject from it. In order to do that you need to use ScalarConvertorsFactory and your method will look like

getTimeSessionsCall.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<String> call, Response<String> response) {

           // Get the string and convert to JSONObject

        }

        @Override
        public void onFailure(Call<String> call, Throwable t) {

        }
    });

Don't forget to add

compile 'com.squareup.retrofit2:converter-scalars:2.1.0' and add the convertor factory when you build the Retrofit instance using addConvertorFactory(ScalarsConvertorFactory.create())

ashkhn
  • 1,642
  • 1
  • 13
  • 18
  • To use latest versions of converts visit this [link](https://futurestud.io/tutorials/retrofit-2-introduction-to-multiple-converters) – hasnain_ahmad Oct 30 '17 at 14:06
1

I suggest using GsonConverterFactory.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.example.com")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

You can use this tool to create your json object based on the schema of your json response. Using these tools you can just enjoy the magic as it converts your JSON into Java objects.

2hamed
  • 8,719
  • 13
  • 69
  • 112
  • I think the reason he's trying to convert it to json is even if the model classes are generated he may not need all of them.. So they will just increase the size of his project, increase complexity and memory consumption – ashkhn Jan 10 '17 at 14:04