【问题标题】:How to fetch JSON array without any key in Retrofit?如何在 Retrofit 中获取没有任何键的 JSON 数组?
【发布时间】:2020-10-30 23:09:57
【问题描述】:

我有一个没有任何对象(键)的 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);

【问题讨论】:

  • 在改造界面中向我们展示您尝试了什么
  • @ErwinKurniawanA:我已经编辑了
  • 您是否尝试过使用 List,因为响应都是数字?
  • @ErwinKurniawanA:更改后,我仍然在失败中的第​​ 1 行第 1 列路径 $ 处输入 End of

标签: android json retrofit okhttp


【解决方案1】:

要解析这样一个数组,你可以使用JSONArray as :

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

在这种情况下,我们使用其键从JSON 响应中提取Array 字符串,然后将字符串解析为JSONArray

请记住,我使用的是JSONArray,即org.json.JSONArray,而不是JsonArray,即GSON

【讨论】:

  • JSON 数组没有键
  • @ANdroid 这就是我写这篇文章的原因 -> val jsonArray = JSONArray(yourArrayString).
【解决方案2】:

请尝试以下:

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

           }
       });

【讨论】:

  • 我没有检查。请检查并告诉我
  • 用你的代码试过了。得到与 java.io.EOFException 相同的错误:第 1 行第 1 列路径 $ 的输入结束
【解决方案3】:

您是否尝试编写自己的反序列化器?下面用 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 反序列化器:https://www.javadoc.io/static/com.google.code.gson/gson/2.8.6/com.google.gson/com/google/gson/JsonDeserializer.html

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    相关资源
    最近更新 更多