美文网首页
Retrofit + OKHTTP POST在body中发送Js

Retrofit + OKHTTP POST在body中发送Js

作者: 随风飘丶 | 来源:发表于2021-04-26 11:02 被阅读0次

    举个例子:
    post在body中发送这个字符串 {"imei":"860475034"} , 服务器会解析成 {\"imei\":\"860475034\"}

    报错如下:

    {"status":500,"message":"JSON parse error: Cannot construct instance of `java.util.LinkedHashMap` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{\"imei\":\"860475034\"}'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `java.util.LinkedHashMap` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{\"imei\":\"860475034\"}')\n at [Source: (PushbackInputStream); line: 1, column: 1]"}
    

    各种尝试后如下解决,在Retrofit 初始化时加入 ScalarsConverterFactory 并且对 GsonConverterFactory初始化进行修改,具体代码如下:

    Retrofit.Builder()
                .baseUrl(NetUrl.BASE_URL)
                .addConverterFactory(ScalarsConverterFactory.create()) // 加入这一行
                .addConverterFactory(
                    GsonConverterFactory.create(
                        GsonBuilder().disableHtmlEscaping().create() // 加入这一行
                    )
                )  
                .client(okHttpClient)
                .build()
    
    

    gradle文件,版本自己修改:

    implementation 'com.squareup.retrofit2:converter-scalars:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    

    搞定,么么哒~~

    相关文章

      网友评论

          本文标题:Retrofit + OKHTTP POST在body中发送Js

          本文链接:https://www.haomeiwen.com/subject/ufgsrltx.html