简体   繁体   English

如何使用 retrofit 解析 JSON 响应

[英]How to parse a JSON response with retrofit

So, I have given an API that returns this on a POST call所以,我给出了一个 API,它在 POST 调用中返回了这个

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

And since this is a list but is not good formated from the backend I dont know how to get it from Android, this is what I have tried因为这是一个列表,但从后端格式化不好,我不知道如何从 Android 获取它,这就是我尝试过的

WebService网络服务

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

CodesResponse代码响应

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

Repository资料库

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

But his is outping Null as the response, I really dont know how to bring those different objects that are supposed to be an array of object but instead they are all inside one object但是他的响应超过了 Null,我真的不知道如何将那些应该是 object 数组的不同对象放在一个 object 中

Any idea?任何的想法?

API INPUTS API 输入

member_id    as text string

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

API OUTPUTS API 输出

code_id: as a String code_id:作为一个字符串

name: as a String名称:作为字符串

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

EDIT编辑

the values can be more than those 3 I posted, it depends on how many the response returns值可以超过我发布的 3 个值,这取决于响应返回的数量

suppose you have response like that假设你有这样的反应

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

then you can get a list of values ignoring keys like:然后您可以获得忽略键的值列表,例如:

    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 + "\"");
    }

Are field names JHK LKJ OEN always the same?字段名称JHK LKJ OEN是否始终相同? You said there can be more than 3, what will be the other name when it's more than 3?你说可以有3个以上,超过3个又叫什么?

AbdelraZek posted a great solution to this problem: https://stackoverflow.com/a/64246981/14259754 AbdelraZek 针对这个问题发布了一个很好的解决方案: https://stackoverflow.com/a/64246981/14259754

My version of it in Kotlin with Retrofit in mind:我的版本是 Kotlin,记住 Retrofit:

Retrofit: 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.

Then, wherever you need, just do the following:然后,无论您需要什么,只需执行以下操作:

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

This way you can work with Json response that is unknown to you.这样您就可以使用您不知道的 Json 响应。

It will return null because the JSON inside has different keys("JHK", "LKJ" etc).它会返回 null,因为里面的 JSON 有不同的键(“JHK”、“LKJ”等)。 As Retrofit uses GSON, you need to create a variable with the same name as JSON keys.由于 Retrofit 使用 GSON,因此您需要创建一个与 JSON 键同名的变量。 You will have to use JSONObject and parse the response.您将必须使用 JSONObject 并解析响应。

Instead of using @POST("get_user_codes.php") suspend fun getUserCodesByMemberId(@Body member_id:String): CodesResponse而不是使用@POST("get_user_codes.php") suspend fun getUserCodesByMemberId(@Body member_id:String): CodesResponse

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM