0

I have a JSON array without any object(key) inside which there are JSON Objects like this :

[ 137, 80, 78, 71, 13, 10, 26, 10 ]

I tried to parse it but can't find success can anyone suggest me how to parse this type of Response using Retrofit?

Till now what I am done is in the Activity I have done like:-

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Api.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create()) //Here we are using the GsonConverterFactory to directly convert json data to object
                .build();

    Api api = retrofit.create(Api.class);

    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("userName", "none\\\\Android");

    Call call = api.getUserIcon(jsonObject);

//        Displaying the user a loader with the specific message
        dialog.setMessage("Loading... Please wait...");
        dialog.show();

    call.enqueue(new Callback<Integer>() {
        @Override
        public void onResponse(Call<Integer> call, Response<Integer> response) {
            if (response.isSuccessful()) {
                if (dialog.isShowing())
                    dialog.dismiss();
                

            } else {
                if (dialog.isShowing())
                    dialog.dismiss();
//                    if successfully not added
                    Toast.makeText(getActivity(), "Failure in Success Response", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<Integer> call, Throwable t) {
            if (dialog.isShowing())
                dialog.dismiss();
            Toast.makeText(getActivity(), "Failure in Parsing", Toast.LENGTH_SHORT).show();
        }
    });

and in the interface I have:-

@Headers({  
        "Content-Type:application/json; charset=utf-8",
        "Content-Encoding:UTF-8",
        "Authorization:Basic bnhvbmVcS2Fua2FTZW46NllrKkNpezc=",
        "appID:Sample Android App",
        "locale:en-US"
})
@POST("Admin/GetRegisteredUserIcon")
Call<List<Integer>> getUserIcon(
        @Body JsonObject body);
4
  • show us what have you tried, in your retrofit interface Commented Jul 10, 2020 at 8:39
  • @ErwinKurniawanA: I have editted Commented Jul 10, 2020 at 8:47
  • have you tried using List<Int> since the response is all number? Commented Jul 10, 2020 at 8:48
  • @ErwinKurniawanA: After changing i am still getting End of input at line 1 column 1 path $ in the failure Commented Jul 10, 2020 at 8:52

3 Answers 3

1

To Parse such an Array, you can use JSONArray as :

//For kotlin
val jsonArray = JSONArray(yourArrayString)
//For Java
JSONArray jsonArray = new JSONArray(yourArrayString);

In case you are extracting it from a JSON response which also contain other objects then you can use JSONObject with it as:

val jsonObject = JSONObject(yourJSONResponse)
val yourJSONArray: String = jsonObject.getString(" Key of Your JSONArray ")
val jsonArray = JSONArray(yourJSONArray)

In this case, we are extracting the Array string from JSON response using its key and then parsing the string as JSONArray later.

Remember that, I've used JSONArray which is org.json.JSONArray instead of JsonArray which of GSON.

Sign up to request clarification or add additional context in comments.

2 Comments

The JSON array has without a key
@ANdroid This is why I wrote this -> val jsonArray = JSONArray(yourArrayString).
0

Please try below:

call.enqueue(new Callback<List<Integer>>() {
           @Override
           public void onResponse(Call<List<Integer>> call, Response<List<Integer>> response) {
              
           }

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

           }
       });

2 Comments

I didn't check. Please check and let me know
tried with your code. getting the same error as java.io.EOFException: End of input at line 1 column 1 path $
0

Do you try to write your own Deserializer? Code below written in Kotlin:

       class YourDeserializer: JsonDeserializer<List<Int>>{
    
                override fun deserializer(
                json: JsonElement,
                typeOfT: Type?,
                context: JsonDeserializationContext?         
        ) {
            val jsonArray = json.asJsonObject.get("KeyOfArray").asJsonArray

            var yourArray = mutableListOf<Int>()

            jsonArray.forEach {
                val num = it.asInt
                yourArray.add(num)
            }

            return yourArray.toList()
        }
 }

And when you create your retrofit:

val gson = GsonBuilder().registerTypeAdapter(List::class.java,YourDeserializer()).create()  

    Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(Api.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson)) 
                    .build();

/*Attention: You also need to change your Callback<Integer> to Callback<List<Integer>>, Response<Integer> to Response<List<Integer>> and Call<Integer> to Call<List<Integer>> in your code presented above, so does your fetcher API.*/

To learn more, please refer to

Json Deserializer: https://www.javadoc.io/static/com.google.code.gson/gson/2.8.6/com.google.gson/com/google/gson/JsonDeserializer.html

Gson Builder:https://www.javadoc.io/static/com.google.code.gson/gson/2.8.6/com.google.gson/com/google/gson/GsonBuilder.html

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.