我是使用Retrofit的新手,所以我从服务器获取了此JSON
{
"results_found": 572,
"results_start": 0,
"results_shown": 20,
"restaurants": [
{
"restaurant": {
"R": {
"has_menu_status": {
"delivery": -1,
"takeaway": -1
},
"res_id": 18941862
},
"apikey": "c3abca45d8387e5b1c900563f1d63193",
"id": "18941862",
"name": "Pizza Maru",
"url": "https://www.zomato.com/jakarta/pizza-maru-1-thamrin?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"location": {
"address": "Grand Indonesia Mall, East Mall, Lantai 3A, Jl. M.H. Thamrin No. 1, Thamrin, Jakarta",
"locality": "Grand Indonesia Mall, Thamrin",
"city": "Jakarta",
"city_id": 74,
"latitude": "-6.1954467635",
"longitude": "106.8216102943",
"zipcode": "",
"country_id": 94,
"locality_verbose": "Grand Indonesia Mall, Thamrin, Jakarta"
},
"switch_to_order_menu": 0,
"cuisines": "Pizza",
"timings": "10 AM to 10 PM",
"average_cost_for_two": 180000,
"price_range": 3,
"currency": "IDR",
"highlights": [
"Credit Card",
"Delivery",
"No Alcohol Available",
"Dinner",
"Debit Card",
"Lunch",
"Cash",
"Takeaway Available",
"VAT",
"Air Conditioned",
"Wifi",
"Service Charge",
"Indoor Seating",
"Table booking recommended"
],
"offers": [],
"opentable_support": 0,
"is_zomato_book_res": 1,
"mezzo_provider": "ZOMATO_BOOK",
"is_book_form_web_view": 0,
"book_form_web_view_url": "",
"thumb": "https://b.zmtcdn.com/data/pictures/chains/2/18941862/403aa36cb046e86a694e7989bb7cd545.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
"user_rating": {
"aggregate_rating": "4.4",
"rating_text": "Sangat Baik",
"rating_color": "5BA829",
"rating_obj": {
"title": {
"text": "4.4"
},
"bg_color": {
"type": "lime",
"tint": "700"
}
},
"votes": "928"
},
"all_reviews_count": 739,
}
我有几个类可以将该JSON映射为kotlin类
基本回应:
data class RestaurantListBaseResponse (
@SerializedName("results_found")
val results_found : Int = 0,
@SerializedName("results_start")
val results_start : Int = 0,
@SerializedName("results_shown")
val results_shown : Int = 0,
@SerializedName("restaurants")
val restaurants : ArrayList<Restaurant> = ArrayList()
)
餐厅类
data class Restaurant (
@SerializedName("id")
val id : Int,
@SerializedName("name")
val name : String,
@SerializedName("url")
val url : String,
@SerializedName("location")
val location : Location,
@SerializedName("currency")
val currency : String,
@SerializedName("phone_numbers")
val phone_numbers : String
)
和位置
data class Location (
@SerializedName("address")
val address : String = "",
@SerializedName("city")
val city : String = "",
@SerializedName("latitude")
val latitude : Double = 0.0,
@SerializedName("longitude")
val longitude : Double = 0.0,
@SerializedName("zipcode")
val zipcode : String = ""
)
我实际上可以将数据获取到android,但是当我访问restaurant属性的值时,对象属性中的所有值都为null
[餐厅(id = 0,名称=空,网址=空,位置=空,货币=空,
phone_numbers = null),Restaurant(id = 0,name = null,url = null,
location = null,currency = null,phone_numbers = null)]
但是我可以得到
results_found
的值(不是null),它是RestaurantListBaseResponse
的属性,因此将Restaurant JSON映射为kotlin时遇到问题。
如您所见,restaurant类并不具有JSON的所有属性,我只是编写了重要的属性。这有问题吗?请帮忙。
这是API接口
interface RestaurantAPI {
@Headers("user-key: $USER_KEY_ZOMATO")
@GET("search")
fun searchRestaurants(
@Query("radius") radius: Int,
@Query("q") searchedKeyword: String,
@Query("lat") latitude: Double,
@Query("lon") longitude: Double
): Call<RestaurantListBaseResponse>
}
这是服务生成器
object RetrofitServiceGenerator {
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(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build()
fun <T> getInstance(APIType: Class<T>) : T {
return retrofit.create(APIType)
}
}
我用这段代码称呼它
val restaurantService = RetrofitServiceGenerator.getInstance(RestaurantAPI::class.java)
val requestCall = restaurantService.searchRestaurants(1000,"pizza",-6.219225,106.834572)
requestCall.enqueue(object: Callback<RestaurantListBaseResponse> {
override fun onFailure(call: Call<RestaurantListBaseResponse>, t: Throwable) {
}
override fun onResponse(call: Call<RestaurantListBaseResponse>, response: Response<RestaurantListBaseResponse>) {
Log.d("debug","result found: ${response.body()!!.results_found}") // I can get the value
val x = response.body()!!.restaurants
Log.d("debug","list of resto: ${x.toString()}") // the properties is null
}
})
java或kotlin都可以
最佳答案
只需使用val从数据类中删除所有初始化即可。或使用var代替val。
您已经在初始化val值,因此您无法重新分配它们。