提问者:小点点

如何使用Rovfit解析JSON响应


因此,我给出了一个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))
    }

但是他的响应是输出空,我真的不知道如何带来那些不同的对象,这些对象应该是一个对象数组,但实际上它们都在一个对象中

知道吗?

member_id    as text string

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

CODE_ID:作为字符串

名称:作为字符串

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

共2个答案

匿名用户

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

而不是使用@post(“get_user_codes.php”)挂起fun getUserCodesByMemberId(@body member_id:string):CodesResponse

使用@post(“get_user_codes.php”)suspend fun getUserCodesByMemberId(@body member_id:string):JSONObject

匿名用户

假设你有这样的回应

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