Ale*_*289 -1 android kotlin retrofit2
所以从服务器我会得到这样的JSON:
{
"success": "1",
"data": [
{
"id": 1,
"title": "1",
"url": "5",
"image": "resources/assets/images/banner_images/1548316546.mitra lakuin.png",
"type": "category"
},
{
"id": 2,
"title": "2",
"url": "5",
"image": "resources/assets/images/banner_images/1548316605.mobile banner_-02 (1).png",
"type": "category"
},
{
"id": 4,
"title": "4",
"url": "5",
"image": "resources/assets/images/banner_images/1547010221.gratis ongkir.png",
"type": "category"
},
{
"id": 5,
"title": "Customer",
"url": "5",
"image": "resources/assets/images/banner_images/1548316659.customer service.png",
"type": "category"
}
],
"message": "Banners are returned successfull."
}
Run Code Online (Sandbox Code Playgroud)
我创建了2个类,以便将该JSON转换为Banner对象.
// 1.
class BannerData(val message : String, val success : String, val data : List<Banner>) {}
// 2.
class Banner(id: Int, imageURL: String) {
@SerializedName("image")
var imageURL : String
val id : Int
init {
Log.i("testX","triggered")
this.id = id
// The code below is used to add percent encoding to URL from server
val unformattedFullPath = "${Endpoint.lakuin}/$imageURL"
val formattedFullPath = URLConverterService.addingPercentEncoding(unformattedFullPath)
this.imageURL = formattedFullPath
}
}
Run Code Online (Sandbox Code Playgroud)
改造界面是这样的:
@GET("/app/getbanners")
fun getBanners(): Call<BannerData>
Run Code Online (Sandbox Code Playgroud)
界面构建器是这样的:
object RetrofitHandler {
private val loggingInterceptor = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
private val okHttpClient = OkHttpClient.Builder()
.callTimeout(7,TimeUnit.SECONDS)
.addInterceptor(loggingInterceptor)
.build()
private var retrofit = Retrofit.Builder()
.baseUrl(Endpoint.lakuin) // default is set to lakuinAPI
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build()
fun <T> getInstance(APIType: Class<T>) : T {
// baseURL should be change later, if there is more than one API, ex: GoogleMapAPI, LakuinAPI etc
return retrofit.create(APIType)
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是......
从上面的JSON可以看出,图像URL不完整,我想转换imageURL
来自:"resources/blablabla.png"
将:" http://xxxx.com/resources/blablabla.png "
我尝试在Banner类中的init块内转换它.
但是.....似乎类中的init块Banner永远不会被触发,我尝试记录它但我在logcat中找不到,那Log.i("testX","triggered")从未在logcat中显示
我实际上可以创建Banner对象,但imageURL与JSON完全相同,这意味着永远不会触发init块

那么这里出了什么问题?
如果你设置改造使用Gson库作为序列化/反序列化对象的库addConverterFactory(GsonConverterFactory.create(gson)),Gson默认情况下不使用构造函数或init函数,instantiate an object and set its fields via reflection所以我猜你的init块只是跳过,看看Gson库,了解你是否可以配置为不跳过init功能.
| 归档时间: |
|
| 查看次数: |
68 次 |
| 最近记录: |