【问题标题】:How to parse a JSON response with retrofit如何通过改造解析 JSON 响应
【发布时间】:2021-01-22 13:35:47
【问题描述】:

所以,我给出了一个 API,它在 POST 调用中返回它

{
 "JHK":"One piece",
 "LKJ":"Two pieces",
 "OEN":"Three pieces"
}

由于这是一个列表,但从后端格式不好,我不知道如何从 Android 获取它,这是我尝试过的

网络服务

@POST("get_user_codes.php")
suspend fun getUserCodesByMemberId(@Body member_id:String): CodesResponse

代码响应

data class CodesResponse(val data: List<Code>)
data class Code(val code_id:String,val name:String)

存储库

suspend fun getUserCodes(memberId:String):Result<CodesResponse>{
        return Result.Success(webService.getUserCodesByMemberId(memberId))
    }

但是他的响应超过了 Null,我真的不知道如何带来那些应该是对象数组但它们都在一个对象内的不同对象

有什么想法吗?

API 输入

member_id    as text string

Example of input:
{ "member_id": "1"}

API 输出

code_id:作为字符串

名称:作为字符串

 {
     "JHK":"One piece",
     "LKJ":"Two pieces",
     "OEN":"Three pieces"
    }

编辑

值可以超过我发布的 3 个,这取决于响应返回的数量

【问题讨论】:

  • 你总是得到一个包含 3 个项目的 api 响应,还是只有 1 个项目并且它从 3 个迭代?例如它总是 JHK 和 LKJ 和 OEN 还是它是“或”而不是“和”
  • 可以超过3个

标签: android kotlin mvvm retrofit retrofit2


【解决方案1】:

假设你有这样的回应

 String json = {
                "JHK":"One piece",
                "LKJ":"Two pieces",
                "OEN":"Three pieces"
}

然后您可以获得忽略键的值列表,例如:

    ArrayList<String> arr = new ArrayList<>();
    try {

        JSONObject response = new JSONObject(json);
        Iterator keys = response.keys();

        while (keys.hasNext()) {
            // loop to get the dynamic key
            String currentKey = (String) keys.next();

            // get the value of the dynamic key
             String value = response.getJSONObject(currentKey).toString();
            arr.add(value);
        }


    } catch (Throwable t) {
        Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
    }

【讨论】:

    【解决方案2】:

    字段名称JHK LKJ OEN 总是相同吗?你说可以多于3个,多于3个又叫什么名字?

    AbdelraZek 为这个问题发布了一个很好的解决方案:https://stackoverflow.com/a/64246981/14259754

    我在 Kotlin 中使用 Retrofit 的版本:

    改造:

    // Here we use ScalarsConverter to be able to return String as a response.
    Retrofit.Builder()
    .baseUrl("http://YourURL")
    .addConverterFactory(ScalarsConverterFactory.create())
    .build()
    .create(YourInterfaceClass::class.java)
    
    
    // Then you can proceed to your POST function
    suspend fun getUserCodesByMemberId(@Body member_id:String): String
    
    // I suggest using Response<String> so you can check the response code and process it if needed.
    

    然后,无论您需要什么,只需执行以下操作:

    val response = getUserCodesByMemberId
    
    val json = JSONObject(response.body()!!) 
    val array = mutableListOf<String>()
    
    val keys: Iterator<String> = json.keys()
    while (keys.hasNext()) {
      val key = keys.next()
      array.add(json[key].toString())
    }
    

    这样您就可以处理您不知道的 Json 响应。

    【讨论】:

    • 它可以超过 3 ,无论新值进来
    【解决方案3】:

    它会返回 null 因为里面的 JSON 有不同的键(“JHK”、“LKJ”等)。 由于 Retrofit 使用 GSON,您需要创建一个与 JSON 键同名的变量。您必须使用 JSONObject 并解析响应。

    而不是使用 @POST("get_user_codes.php") 暂停乐趣 getUserCodesByMemberId(@Body member_id:String): CodesResponse

    使用 @POST("get_user_codes.php") 暂停乐趣 getUserCodesByMemberId(@Body member_id:String): JSONObject

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 2020-03-19
      • 2015-08-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      相关资源
      最近更新 更多