【发布时间】:2019-11-01 11:40:48
【问题描述】:
嗨,我正在尝试用 kotlin 解析 JSON
下面是我的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"}]
}]
请注意这个 json 响应以数组开头
这是我的类来解析它
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
}
这是我的代码
//interface
interface SemdetailsFetcher {
@GET("test/json/sub1.json")
fun getCurrentSemData(): Call<SemdetailsPArser>
}
这是我的活动代码
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)
}
}
})
}
我收到了这个错误
here 3 com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
我知道这可能与我的解析类有关
这里我得到了一个 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
}
当我更改解析类和接口时,它工作得很好
我的问题是我不知道如何编写一个类来解析以数组开头的 json 响应
【问题讨论】:
-
您的解析将不起作用,因为您的响应是 json 数组并且您编写的代码需要一个 json 对象响应
-
是的,我明白了,你能解释一下如何实现吗?我尝试了在线 gson 生成器,上面的类是使用相同的 json 输入生成的