提问者:小点点

为什么当我解析我的响应时,okHttp不起作用。


所以这是我的问题,我尝试解析对象的 json 数组,但抛出了一个错误。我创建了一个 groupListType var,因为 Gson 没有解析我的对象并让我使用字符串数组,这给了我错误

这是函数的代码:

fun getPromoCode(): Array<Code> {


        val urlBuilder = HttpUrl.Builder()
            .scheme("https")
            .host("dev.api.gostyle.ovh")
            .addPathSegment("api")
            .addPathSegment("promotion")
            .addPathSegment("code")
            .addQueryParameter("user_id",sharedPreference.getValueString("UserId"))
            .build()


        var request = Request.Builder()
            .header("Authorization",sharedPreference.getValueString("MyGoStyleToken"))
            .url(urlBuilder)
            .build()


        var mareponse = client.newCall(request).execute()

            if (!mareponse.isSuccessful) throw IOException("Unexpected code $mareponse")

            var a: String = mareponse.body?.string().toString()
            val groupListType: Type = object: TypeToken<ArrayList<Code>>() {}.type
            var test = Gson().fromJson<Array<Code>>(a,groupListType) //Error here

            return test
    } 

我的数据类:

data class Code(
    var id: String = "default",
    var code:String = "default",
    var date_start:String = "default",
    var date_end:String = "default",
    var description: String = "default",
    var reduction: Double = 0.0
)

错误日志:

E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
    Process: com.example.mygostyle, PID: 13854
    java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.example.mygostyle.Code[]
        at com.example.mygostyle.OkHttpHelper.getPromoCode(OkHttpHelper.kt:95)
        at com.example.mygostyle.ui.home.HomeFragment$MyCodesAdapter.<init>(HomeFragment.kt:72)
        at com.example.mygostyle.ui.home.HomeFragment$onCreateView$2.run(HomeFragment.kt:40)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
        at java.lang.Thread.run(Thread.java:764)

json对象示例:

[
    {
        "id": "77fa026a-d519-40ec-ad03-a0532036473f",
        "code": "TEST1",
        "date_start": "2020-02-10T00:00:00.000Z",
        "date_end": "2020-02-10T00:00:00.000Z",
        "description": "TEST1",
        "reduction": 20
    },
    {
        "id": "8bade40a-33e5-4eee-a093-6b778c89df32",
        "code": "TEST2",
        "date_start": "2020-02-10T00:00:00.000Z",
        "date_end": "2020-02-10T00:00:00.000Z",
        "description": "TEST2",
        "reduction": 30
    }
]

共1个答案

匿名用户

ArrayArrayList是不同的类型。你只需要这样:

val result: Array<Code> = Gson().fromJson(a, Array<Code>::javaClass)
// use `result.toList()` if you need a list instead of an array

额外链接:

  • https://stackoverflow.com/a/45605731/4751657
  • https://stackoverflow.com/a/18421994/4751657