我有一个包含未知键(数字)的JSON响应,我发现使用Gson转换器很难解析它。
{
"list": {
"14": {
"nickname": "Dave",
"fullname": "David Collins"
},
"68": {
"nickname": "Phil",
"fullname": "Phillip Jordan"
}
},
"action": "load",
"status": "LOADED"
}
下面的类结构给出错误Expected BEGIN_OBJECT but was NUMBER at line 1 column 23 path $.list..
data class NameNW(
val fullname: String,
val nickname: String
)
data class NamesListNWEntity(
val action: String,
val list: Map<Int, Map<String, NameNW>>,
val status: String
)
我不知道为什么当类型是Map〈Int...(或者它没有看到数字前面的'{',而它明明在那里),所以我就被困在这里了。我如何让它解析字符串?更好的是,我如何让它记录NameNW的数字?如果不可能,我可以调整服务器的输出,但这意味着还要在Web客户端上更新大量代码,而我宁愿避免这样做。
我的改装代码是
interface Network {
@FormUrlEncoded
@POST("serverfile")
suspend fun getNames(
@Field("action") action: String,
): NamesListNWEntity
}
class RetrofitWithCookie @Inject constructor(
context: Context,
gson: Gson
) {
private val mContext = context
private val gson = gson
fun createRetrofit(): Retrofit {
val client: OkHttpClient
val builder = OkHttpClient.Builder()
builder.addInterceptor(AddCookiesInterceptor(mContext))
builder.addInterceptor(ReceivedCookiesInterceptor(mContext))
client = builder.build()
return Retrofit.Builder()
.baseUrl("http://192.168.0.19/")
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
}
}
我使用瓦尔namesListNWEntity = Network.getNames(“load”)调用它
1条答案
按热度按时间uqxowvwt1#
请尝试使用以下代码。