【发布时间】:2019-07-27 05:10:20
【问题描述】:
我有以下从 WordPress 帖子生成的 json:
{
"events":[
{
"id":4651,
"title":"Test title",
"description":"testttt",
"image": {
url: "https://myhost.tv/wp-content/uploads/2019/07/event2.jpg",
id: "4652"}
}
]
}
我的json模型如下:
data class EventsFeed(val events: Array<Events>)
data class Events (
val id : Int,
val title : String,
val description : String,
val image : Image
)
data class Image (
val url : String,
val id : Int,
)
我使用 Json 进行解析,一切正常,但是当我在 wordpress 中进行 POST 并且我没有放置图像时,Image 键的值将我设置为false,如下所示:
{
"events":[
{
"id":4651,
"title":"Stand Up Comedy",
"description":"testttt",
"image":false
}
]
}
因为image 的值是false,所以解析会返回错误:Expected BEGIN_OBJECT but was BOOLEAN at line 1 column 5781 path $ .events [1] .image
当帖子没有图像可以正确解析时忽略false 的值,或者无论如何如果它是false,我该怎么做,请将其保留为默认图像 (https://myhost.com/image_defaul.jpg)
json 由 Wordpress 插件生成:活动日历:Demo json here
我的解析函数(使用Volley和Gson)如下(将数据数组发送到适配器以在recyclerview中显示)
fun jsonObjectRequest() {
Log.i(LOG_TAG, "jsonObjectRequest")
// Instantiate the RequestQueue.
val queue = Volley.newRequestQueue(activity)
val url = "https://myhost.tv/wp-json/tribe/events/v1/events"
// Request a JSONObject response from the provided URL.
val jsonObjectRequest = JsonObjectRequest( url, null,
Response.Listener { response ->
Log.i(LOG_TAG, "Response is: $response")
val gson = Gson()
val homeEvents = gson.fromJson(response.toString(), EventsFeed::class.java)
activity?.runOnUiThread {
recyclerEvents.adapter = AdaptadorEventos(homeEvents)
}
},
Response.ErrorListener { error ->
error.printStackTrace()
Log.e(LOG_TAG, "That didn't work!")
}
)
// Add the request to the RequestQueue.
queue.add(jsonObjectRequest)
}
【问题讨论】:
-
首先,您应该更改服务器响应,以便在没有图像时将图像字段设置为空。第二种解决方案是您必须手动解析 jsonparser 的响应。