Get nested JSON object with GSON using retrofit

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

    Bit late but hopefully this will help someone.

    Just create following TypeAdapterFactory.

        public class ItemTypeAdapterFactory implements TypeAdapterFactory {
    
          public  TypeAdapter create(Gson gson, final TypeToken type) {
    
            final TypeAdapter delegate = gson.getDelegateAdapter(this, type);
            final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class);
    
            return new TypeAdapter() {
    
                public void write(JsonWriter out, T value) throws IOException {
                    delegate.write(out, value);
                }
    
                public T read(JsonReader in) throws IOException {
    
                    JsonElement jsonElement = elementAdapter.read(in);
                    if (jsonElement.isJsonObject()) {
                        JsonObject jsonObject = jsonElement.getAsJsonObject();
                        if (jsonObject.has("content")) {
                            jsonElement = jsonObject.get("content");
                        }
                    }
    
                    return delegate.fromJsonTree(jsonElement);
                }
            }.nullSafe();
        }
    }
    

    and add it into your GSON builder :

    .registerTypeAdapterFactory(new ItemTypeAdapterFactory());
    

    or

     yourGsonBuilder.registerTypeAdapterFactory(new ItemTypeAdapterFactory());
    

提交回复
热议问题