我正在尝试从此服务器响应中提取“级别”。我对Android开发有点陌生。我需要解析此API响应到POJO列表的帮助。

    {
  "levels": [
    {
      "id": 1,
      "level": 0,
      "name": "Level 0"
    },
    {
      "id": 2,
      "level": 1,
      "name": "Level 1"
    }
  ]
}


该级别的kotlin数据类:

data class Level(var id:Int, var level: Int, var name: String?=null)


这是自定义的Gson反序列化器
JsonDeserializer:

public class RestDeserializer<T> implements JsonDeserializer<T> {
    private Class<T> clasz;
    private String key;

    public RestDeserializer(Class<T> clasz, String key) {
        this.clasz = clasz;
        this.key = key;
    }

    @Override
    public T deserialize(
            JsonElement jsonElement,
            Type type,
            JsonDeserializationContext jsonDeserializationContext
    ) throws JsonParseException{
        JsonElement content = jsonElement.getAsJsonObject().get(key);
        return new Gson().fromJson(content, clasz);
    }
}


改造客户:

interface LevelService {
    @GET("api/levels")
    fun getLevels():Call<List<Level>>

    companion object {
        fun levels(context: Context): LevelService{
            Gson gson = new GsonBuilder()
                .registerTypeAdapter(Level.class, new RestDeserializer<>(Level[].class, "levels"))
                .create();
val retrofit = Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson))
                .baseUrl(Constants.BASE_URL)
                .client(httpClient.build())
                .build();
            return retrofit.create(LevelService::class.java)
        }
    }
}


最后致电:

fun getLevels(){
        val apiService = LevelService.levels(applicationContext)
        apiService.getLevels().enqueue(object : Callback<List<Level>>{
            override fun onFailure(call: Call<List<Level>>?, t: Throwable?) {
                Log.d("Error: FATAL)", "Error:(")
                t!!.printStackTrace()
            }

            override fun onResponse(call: Call<List<Level>>?, response: Response<List<Level>>?) {
                if (response!!.isSuccessful){

                    Log.d("SUCCESS", response.body().toString())
                }
                else{
                    Log.d("Error:)", response.errorBody().toString())
                }
            }

        })
    }


但是它没有给出错误我希望可以清除它:

java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2


任何帮助是极大的赞赏!!

StakeTrace如下:

 W/System.err: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
        at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:350)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:80)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
        at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:39)
W/System.err:     at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:27)
        at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:122)
        at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:217)
        at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:116)
        at okhttp3.RealCall$AsyncCall.execute(RealCall.java:153)
        at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
        at java.lang.Thread.run(Thread.java:818)

最佳答案

您必须更改RestDeserializer才能从JsonArray获得值,而不是直接从JsonObject获得值。

JsonArray array = je.getAsJsonObject().getAsJsonArray(key);

关于java - 在对象内转换Gson数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51073776/

10-10 23:06