简体   繁体   English

使用 class Kotlin Android 解析 json 时出错

[英]Error in parsing json with class Kotlin Android

hi i am trying to parse JSON with kotlin嗨,我正在尝试用 kotlin 解析 JSON

below is my json code下面是我的 json 代码

    [{
    "module":"1",
    "books":[{"name":"bookname1","authors":"author1, author 2"},
             {"name":"bookname2","authors":"author1, author 2"},
             {"name":"bookname3","authors":"author1, author 2"}]
},
{
    "module":"2",
    "books":[{"name":"bookname1","authors":"author1, author 2"},
             {"name":"bookname2","authors":"author1, author 2"},
             {"name":"bookname3","authors":"author1, author 2"}]
},
{
    "module":"3",
    "books":[{"name":"bookname1","authors":"author1, author 2"},
             {"name":"bookname2","authors":"author1, author 2"},
             {"name":"bookname3","authors":"author1, author 2"}]
},
{
    "module":"4",
    "books":[{"name":"bookname1","authors":"author1, author 2"},
             {"name":"bookname2","authors":"author1, author 2"},
             {"name":"bookname3","authors":"author1, author 2"}]
},
{
    "module":"5",
    "books":[{"name":"bookname1","authors":"author1, author 2"},
             {"name":"bookname2","authors":"author1, author 2"},
             {"name":"bookname3","authors":"author1, author 2"}]
}]

please note that this json response starts with array请注意,此 json 响应以数组开头

here is my class to parse it这是我的 class 来解析它

class SemdetailsPArser {

    @SerializedName("module")
    @Expose
    var module: String? = null
    @SerializedName("books")
    @Expose
    var books: List<Book>? = null




}

class Book {

    @SerializedName("name")
    @Expose
    var name: String? = null
    @SerializedName("authors")
    @Expose
    var authors: String? = null

}

And here is my code这是我的代码

//interface

interface SemdetailsFetcher {
    @GET("test/json/sub1.json")
    fun getCurrentSemData(): Call<SemdetailsPArser>
}

here is my code in activity这是我的活动代码

fun getCurrentData() {
        val retrofit = Retrofit.Builder()
            .baseUrl(BaseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        val service = retrofit.create(SemdetailsFetcher::class.java)
        val call = service.getCurrentSemData()
        call.enqueue(object : Callback, retrofit2.Callback<SemdetailsPArser> {
            override fun onResponse(
                call: retrofit2.Call<SemdetailsPArser>?,
                response: retrofit2.Response<SemdetailsPArser>?
            ) {
               // val thisthig = response?.body();
                println("here 1 ${response?.body().toString()}")
            }

            override fun onFailure(call: Call?, e: IOException?) {
                println("here 2")
            }

            override fun onFailure(call: retrofit2.Call<SemdetailsPArser>?, t: Throwable?) {
                println("here 3 $t")
            }

            override fun onResponse(call: Call, response: Response) {
                if (response.code() == 200) {

                    println("secodn success")
                    val sampleResp = response.body()!!

                    println(sampleResp)
                }
            }


        })
    }

and i am getting this error我收到了这个错误

here 3 com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

I understood that this might be related to my parsing class我知道这可能与我的解析 class 有关

here i am getting an array of json info, i tried the same code with another json在这里,我得到了一组 json 信息,我用另一个 json 尝试了相同的代码

{
    "person": {
        "name": "Don",
        "age": 35
    },
    "books": [{
            "id": 800,
            "name": "book 1",
            "description": "clear sky",
            "icon": "01n"
        },
        {
            "id": 801,
            "name": "book 2",
            "description": "clear sky 1",
            "icon": "01N"
        }
    ],

    "city": "bgvnslsl",
    "id": 1851632,
    "bname": "abcd",
    "code": 200
}

this was working perfectly when i changed the parsing class and interface当我更改解析 class 和接口时,这工作得很好

My problem is that i dont know how to write a class to parse a json response starting with an array我的问题是我不知道如何编写 class 来解析以数组开头的 json 响应

You are expecting list of SemdetailsPArser , so you should define return type as List of SemdetailsPArser您期待SemdetailsPArser列表,因此您应该将返回类型定义为SemdetailsPArser列表

This should fix problem.这应该可以解决问题。

interface SemdetailsFetcher {
    @GET("test/json/sub1.json")
    fun getCurrentSemData(): Call<List<SemdetailsPArser>>
}

You also need to change it in other parts of code.您还需要在代码的其他部分进行更改。

The error you are getting means that you're trying to parse JSON array, thinking it should be JSON object.您收到的错误意味着您正在尝试解析 JSON 数组,认为它应该是 JSON object。 JSON array is the thing between these [] , while JSON object is in curly brackets like these {} . JSON 数组是这些[]之间的东西,而 JSON object 在像这样的大括号中{} So your first JSON corresponds to something like List<Module> , it's not an object, but a list of them.所以你的第一个 JSON 对应于List<Module>之类的东西,它不是 object,而是它们的列表。 Each module has a list of books in it.每个模块都有一个书籍列表。

So all said, it should be like this所以都说应该是这样的

interface SemdetailsFetcher {
    @GET("test/json/sub1.json")
    fun getCurrentSemData(): Call<List<SemdetailsPArser>>
}

By the way, if you define your POJOs right, you won't need all the annotations.顺便说一句,如果您正确定义 POJO,则不需要所有注释。

Create SemdetailsPArser class创建 SemdetailsPARser class

data class SemdetailsPArser( val books: List<Book>, val module: String )

Next create Book class接下来创建书 class

data class Book(
val authors: String,
val name: String

) )

next in the interface (SemdetailsFetcher)界面中的下一步(SemdetailsFetcher)

interface SemdetailsFetcher {
@GET("test/json/sub1.json")
fun getCurrentSemData(): Call<List<SemdetailsPArser>>

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM