[英]How to parse a JSON response with retrofit
所以,我给出了一个 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,我真的不知道如何将那些应该是 object 数组的不同对象放在一个 object 中
任何的想法?
member_id as text string
Example of input:
{ "member_id": "1"}
code_id:作为一个字符串
名称:作为字符串
{
"JHK":"One piece",
"LKJ":"Two pieces",
"OEN":"Three pieces"
}
值可以超过我发布的 3 个值,这取决于响应返回的数量
假设你有这样的反应
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 + "\"");
}
字段名称JHK
LKJ
OEN
是否始终相同? 你说可以有3个以上,超过3个又叫什么?
AbdelraZek 针对这个问题发布了一个很好的解决方案: https://stackoverflow.com/a/64246981/14259754
我的版本是 Kotlin,记住 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.
然后,无论您需要什么,只需执行以下操作:
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 响应。
它会返回 null,因为里面的 JSON 有不同的键(“JHK”、“LKJ”等)。 由于 Retrofit 使用 GSON,因此您需要创建一个与 JSON 键同名的变量。 您将必须使用 JSONObject 并解析响应。
而不是使用@POST("get_user_codes.php") suspend fun getUserCodesByMemberId(@Body member_id:String): CodesResponse
使用@POST("get_user_codes.php") 暂停乐趣 getUserCodesByMemberId(@Body member_id:String): JSONObject
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.