解决 com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expecte

648 阅读1分钟

问题起因

在对聚合数据某个Api返回的Json数据进行解析时,无法成功解析且爆了Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $的error image.png

原因分析

首先查看原始的Json数据 image.png 再查看自己设计的Bean类

class Joke : Serializable { 
    var reason: String? = null 
    var result: List<List<DataBean>>? = null 
    var error_code: Int = -1 
    
    class DataBean : Serializable { 
        var content: String? = null 
        var hashId: String? = null 
        var unixtime: String? = null 
        var updatetime: String? = null 
    } 
}

这个时候我们借助 www.json.cn/ 网站对Json数据进行解析 发现 result 是 Object类 data是一个Array类

image.png

image.png

解决方案

所以我们将Bean类最终设计为如下代码

class Joke : Serializable { 
    var reason: String? = null 
    var result: DataBean? = null 
    var error_code: Int = -1 
    
    class DataBean : Serializable { 
        var data: List<JokeBean>? = null 
    } 
    
    class JokeBean:Serializable{ 
        var content: String? = null 
        var hashId: String? = null 
        var unixtime: String? = null 
        var updatetime: String? = null 
    } 
}

参考文献

blog.csdn.net/ququ9376/ar…