如何获得仅包含 POST 响应最后一部分的字符串?



作为 POST 请求的结果,我得到以下形式的响应:

D/OkHttp: {"msg":"OK","uploadid":"1dd0ff732ca3b0fc3892180b3d67e0df","ids":["5e20fe2a688c775700049d4c"]}

如何获得仅包含响应最后一部分的字符串?示例:string response = "5e20fe2a688c775700049d4c"

从http请求中,您得到的响应就是您到达那里的。您现在需要做的只是这样做:

//response is the string you got from server
JSONObject jobject = new JSONObject(response);
String s = jobject.getString("ids");
TextView.setText("Response string is : " + s);

您可以随时检查系统读取的内容

Log.i("TAG",response);
//and for the element of json
Log.i("Tag",s);
response.body?.string()?.let {
val jsonObject = JSONObject(it)
val ids = jsonObject.getJSONArray("ids")
val id = ids.getString(0)
}

response.body?.string()获取所需的 JSON 字符串。然后,您可以解析该字符串以获取所需的值。GSON 库更常用,但如果您不想导入 GSON,也可以使用内置JSONObject

使用 GSON 库,我从 JSON 文件中获取了 Kotlin 类并选择了 null 元素。

// Get Image response Id
val gson = Gson()
val imageResponse = gson.fromJson(response.body()?.string(), ImageResponse::class.java)
imageMediaId  = imageResponse.ids[0]

最新更新