我的应用程序类:
class App(
var id: Int,
var name: String,
var description: String,
var url: String,
var packageName: String,
var appVersion: String,
var iconMediaUUID: String?,
var created: String,
var createdBy: String
) : Serializable
E D I T:我也尝试了
@SerializedName
注释,没有成功。
我的 Retrofit API 调用:
@GET("/api/app-list")
suspend fun getApplications(): Response<List<App>>
API返回的JSON:
[
{
"id": 1,
"name": "facebook",
"description": "face book",
"url": "https://play.google.com/store/apps/details?id=com.facebook.katana",
"packageName": "com.facebook.katana",
"appVersion": "1",
"iconMediaUUID": null,
"created": "2023-09-05 09:20",
"createdBy": "[email protected]"
},
{
"id": 3,
"name": "twitter",
"description": "X",
"url": "https://play.google.com/store/apps/details?id=com.twitter.android",
"packageName": "com.twitter.android",
"appVersion": "43",
"iconMediaUUID": "e2913bc1-4963-4a3e-85bf-8244b5b42979",
"created": "2023-09-05 10:11",
"createdBy": "[email protected]"
}
]
我的Retrofit实例:
private fun getBackendClient(): Retrofit =
Retrofit.Builder()
.client(okHttpClient)
.baseUrl(BACKEND_BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build()
fun callBackend(): Endpoints {
return getBackendClient().create(Endpoints::class.java)
}
记录代码:
val response: Response<List<App>> = API.callBackend().getApplications()
if (response.isSuccessful) {
val appList = response.body()
if (appList != null) {
Log.i("PARSED_", "size of list: "+appList.size)
for (app in appList) {
Log.i("PARSED_", "id: " + app.id + ", name: " + app.name)
}
}
}
但是,我的解析实例仍然每个属性中只有空值,为什么?
日志:
PARSED_ size of list: 2
PARSED_ id: null, name: null
PARSED_ id: null, name: null
为什么不起作用?
在使用 Retrofit 处理 JSON 响应时,您看到的所有
App
类的属性均为 null 的问题很可能是由于 JSON 键与 App
类中的字段名称之间的命名不匹配造成的。要解决此问题,请使用 Gson 库的 @SerializedName
注释来注释“App”类字段,以清楚地描述 JSON 键和类字段之间的映射。以下是更改您的 App
班级的方法:
import com.google.gson.annotations.SerializedName
class App(
@SerializedName("id")
var id: Int,
@SerializedName("name")
var name: String,
@SerializedName("description")
var description: String,
@SerializedName("url")
var url: String,
@SerializedName("packageName")
var packageName: String,
@SerializedName("appVersion")
var appVersion: String,
@SerializedName("iconMediaUUID")
var iconMediaUUID: String?,
@SerializedName("created")
var created: String,
@SerializedName("createdBy")
var createdBy: String
) : Serializable
您可以通过向每个字段添加
@SerializedName
注释来明确指示 JSON 键和类字段之间的映射。这允许 Gson 正确读取 JSON 响应并将相关属性值插入到您的 App
类中。