【问题标题】:Kotlin Volley POST Request: ParseError || Value Hat of type java.lang.String cannot be converted to JSONObject.messageKotlin Volley POST 请求:ParseError || java.lang.String 类型的值 Hat 无法转换为 JSONObject.message
【发布时间】:2021-02-02 01:22:40
【问题描述】:

将 JSONObject 发布到我的网络服务时,我总是收到以下错误:

I/System.out:错误 com.android.volley.ParseError:org.json.JSONException:java.lang.String 类型的 Value Hat 无法转换为 JSONObject.message

总是显示 VolleyError。

Json 看起来像这样:{"channel1":255,"channel2":255,"channel3":0}

生成 JSON 的代码:

data class DMX(
        var channel1: Int = 0,
        var channel2: Int = 0,
        var channel3: Int = 0,
    )
val DMXValues = DMX(255, 255, 0)
val j = Gson().toJson(DMXValues)
val json = JSONObject(j)

我的 Web 服务处理得很好,没有错误。 但什么是“价值帽子”?在 Google 上没有找到任何东西...

我的代码:

val jsonRequest = JsonObjectRequest(Request.Method.POST, url, json, { response ->
        Toast.makeText(applicationContext, response.toString(), Toast.LENGTH_SHORT).show()
    },
        {error: VolleyError ->
            println("Error $error.message")
            Toast.makeText(applicationContext, "Didn't work!", Toast.LENGTH_SHORT).show()

        })

【问题讨论】:

    标签: android android-studio kotlin android-volley parse-error


    【解决方案1】:

    您能否发布您用于获取此错误的确切 json,基本上您的 json 字符串在转换为 JSONObject 时有错误(语法错误 - 在源字符串中或重复的键中)。

    带有帖子正文的字符串请求的示例 kotlin 版本,

    val stringRequest: StringRequest = object : StringRequest(httpMethod, url, Response.Listener { response ->
                // on response implementation
            }, Response.ErrorListener { error ->
                //on error implementation
            }) {
                @Throws(AuthFailureError::class)
                override fun getHeaders(): Map<String, String> {
                    return httpHeaders ?: java.util.HashMap()
                }
    
                @Throws(AuthFailureError::class)
                override fun getBody(): ByteArray {
                    // return your body here
                    return 'you body'
                }
            }
    

    【讨论】:

    • 添加了这个。但是打印出我的 JSON 给出了一个像上面给出的有效的。
    • 谢谢,您的 API 响应的是 JSONObject 还是 String?如果您想以字符串形式接收结果,请不要使用 JSONRequest,您可以使用 StringRequest
    • 这是一个 JSONObject POST 请求。所以我需要发布这个。响应可能是字符串。 GET 请求响应是字符串,使用 200。
    • 是的,我可以知道 API 响应值(及其类型),想在你的代码中具体说明 'val jsonRequest' 的类型是什么?,在下面的代码中,val jsonRequest = JsonObjectRequest( Request.Method.POST, url, json, { response -> Toast.makeText(applicationContext, response.toString(), Toast.LENGTH_SHORT).show() }, {error: VolleyError -> println("Error $error.message ") Toast.makeText(applicationContext, "没用!", Toast.LENGTH_SHORT).show() })
    • 对不起,我没有找到如何在 Volley 中获取 API 响应状态 :(
    猜你喜欢
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    • 2018-04-22
    相关资源
    最近更新 更多