All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.launchdarkly.client.JsonHelpers Maven / Gradle / Ivy

package com.launchdarkly.client;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;

abstract class JsonHelpers {
  /**
   * Implement this interface on any internal class that needs to do some kind of post-processing after
   * being unmarshaled from JSON. You must also add the annotation {@code JsonAdapter(JsonHelpers.PostProcessingDeserializableTypeAdapterFactory)}
   * to the class for this to work.
   */
  static interface PostProcessingDeserializable {
    void afterDeserialized();
  }
  
  static class PostProcessingDeserializableTypeAdapterFactory implements TypeAdapterFactory {
    @Override
    public  TypeAdapter create(Gson gson, TypeToken type) {
      return new PostProcessingDeserializableTypeAdapter<>(gson.getDelegateAdapter(this, type));
    }
  }
  
  private static class PostProcessingDeserializableTypeAdapter extends TypeAdapter {
    private final TypeAdapter baseAdapter;
    
    PostProcessingDeserializableTypeAdapter(TypeAdapter baseAdapter) {
      this.baseAdapter = baseAdapter;
    }
    
    @Override
    public void write(JsonWriter out, T value) throws IOException {
      baseAdapter.write(out, value);
    }

    @Override
    public T read(JsonReader in) throws IOException {
      T instance = baseAdapter.read(in);
      if (instance instanceof PostProcessingDeserializable) {
        ((PostProcessingDeserializable)instance).afterDeserialized();
      }
      return instance;
    }
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy