Kotlin Volley POST请求:ParseError ||类型java.lang.String的Value Hat无法转换为JSONObject.message

问题描述

将JSONObject发布到我的Web服务时,总是出现以下错误

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

        })

解决方法

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

带有请求正文的String请求的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'
            }
        }