Get nested JSON object with GSON using retrofit

前端 未结 13 973
挽巷
挽巷 2020-11-22 17:04

I\'m consuming an API from my android app, and all the JSON responses are like this:

{
    \'status\': \'OK\',
    \'reason\': \'Everything was fine\',
    \         


        
13条回答
  •  醉梦人生
    2020-11-22 17:27

    This is the same solution as @AYarulin but assume the class name is the JSON key name. This way you only need to pass the Class name.

     class RestDeserializer implements JsonDeserializer {
    
        private Class mClass;
        private String mKey;
    
        public RestDeserializer(Class targetClass) {
            mClass = targetClass;
            mKey = mClass.getSimpleName();
        }
    
        @Override
        public T deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
                throws JsonParseException {
            JsonElement content = je.getAsJsonObject().get(mKey);
            return new Gson().fromJson(content, mClass);
    
        }
    }
    

    Then to parse sample payload from above, we can register GSON deserializer. This is problematic as the Key is case sensitive, so the case of the class name must match the case of the JSON key.

    Gson gson = new GsonBuilder()
    .registerTypeAdapter(Content.class, new RestDeserializer<>(Content.class))
    .build();
    

提交回复
热议问题