Get nested JSON object with GSON using retrofit

前端 未结 13 750
挽巷
挽巷 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:29

    Continuing Brian's idea, because we almost always have many REST resources each with it's own root, it could be useful to generalize deserialization:

     class RestDeserializer implements JsonDeserializer {
    
        private Class mClass;
        private String mKey;
    
        public RestDeserializer(Class targetClass, String key) {
            mClass = targetClass;
            mKey = key;
        }
    
        @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:

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

提交回复
热议问题