Как получить массив JSON без ключа в Retrofit? - PullRequest
0 голосов
/ 10 июля 2020

У меня есть массив JSON без какого-либо объекта (ключа), внутри которого есть JSON Объекты, подобные этому:

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

Я попытался разобрать его, но не смог добиться успеха, может ли кто-нибудь предложить мне, как разобрать этот тип ответа с помощью Retrofit?

До сих пор то, что я делал, - это действие, которое я сделал например: -

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();
        }
    });

и в интерфейсе у меня: -

@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);

Ответы [ 3 ]

0 голосов
/ 10 июля 2020

Пожалуйста, попробуйте следующее:

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) {

           }
       });
0 голосов
/ 10 июля 2020

Вы пытаетесь написать свой собственный десериализатор? Код ниже, написанный на 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()
        }
 }

И когда вы создаете свою модернизацию:

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.*/

Чтобы узнать больше, обратитесь к

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

0 голосов
/ 10 июля 2020

Для анализа такого массива вы можете использовать JSONArray как:

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

Если вы извлекаете его из ответа JSON, который также содержит другие объекты, вы можете использовать JSONObject с ним как:

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

В этом случае мы извлекаем строку Array из ответа JSON, используя его ключ, а затем анализируем строку как JSONArray позже.

Помните, что я использовал JSONArray, что означает org.json.JSONArray вместо JsonArray, которое из GSON.

...