Gson deserializer with Retrofit converter: just need inner JSON for all responses

前端 未结 2 1353
渐次进展
渐次进展 2021-02-06 15:47

I am working with an API that always responds like so:

{
\"stuff_i_need\": [
    {
        \"title\": \"Hello\"
    },
    {
        \"title\": \"World!\"
    }
         


        
2条回答
  •  隐瞒了意图╮
    2021-02-06 16:20

    Try this

    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("data") && jsonObject.get("data").isJsonObject())
                    {
                        jsonElement = jsonObject.get("data");
                    }
                }
    
                return delegate.fromJsonTree(jsonElement);
            }
        }.nullSafe();
    }}
    

    Next, you have to add it to the Gson object in your RestClient.

    public class RestClient
    {
        private static final String BASE_URL = "your base url";
        private ApiService apiService;
    
        public RestClient()
        {
            Gson gson = new GsonBuilder()
                    .registerTypeAdapterFactory(new ItemTypeAdapterFactory()) // This is the important line ;)
                    .setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'")
                    .create();
    
            RestAdapter restAdapter = new RestAdapter.Builder()
                    .setLogLevel(RestAdapter.LogLevel.FULL)
                    .setEndpoint(BASE_URL)
                    .setConverter(new GsonConverter(gson))
                    .setRequestInterceptor(new SessionRequestInterceptor())
                    .build();
    
            apiService = restAdapter.create(ApiService.class);
        }
    
        public ApiService getApiService()
        {
            return apiService;
        }
    }
    

    Hope it helps...

提交回复
热议问题