使用Retrofit和Gson解析具有未知键的JSON字符串时出现问题

i7uaboj4  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(222)

我有一个包含未知键(数字)的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”)调用它

uqxowvwt

uqxowvwt1#

请尝试使用以下代码。

data class NameNW(
    val fullname: String,
    val nickname: String
)

data class NamesListNWEntity(
    val action: String,
    val list: Map<String, NameNW>,
    val status: String
)

// You can also test with static json string
private fun test() {
    val apiResponse = "{\n" +
            "  \"list\": {\n" +
            "    \"14\": {\n" +
            "      \"nickname\": \"Dave\",\n" +
            "      \"fullname\": \"David Collins\"\n" +
            "    },\n" +
            "    \"68\": {\n" +
            "      \"nickname\": \"Phil\",\n" +
            "      \"fullname\": \"Phillip Jordan\"\n" +
            "    }\n" +
            "  },\n" +
            "  \"action\": \"load\",\n" +
            "  \"status\": \"LOADED\"\n" +
            "}"

    val namesListNWEntity: NamesListNWEntity = Gson().fromJson(apiResponse, NamesListNWEntity::class.java)
}

相关问题