Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gson: Add function result to an object created by toJson()

Tags:

json

gson

gson is such a great serialize/deserialization tool. It's really simple to get a JSON representation of an arbitrary object by using the toJson-function.

Now I want to send the data of my object to the browser to be used within javascript/jQuery. Thus, I need one additional JSON element defining the dom class of the object which is coded within my object as a dynamic/memberless function

public String buildDomClass()

How to add this string to my String created by the toJson function?

Any ideas?

Thanks a lot

like image 680
John Rumpel Avatar asked Oct 21 '22 02:10

John Rumpel


1 Answers

An easy way is to combine a TypeAdapterFactory and an interface.

First an interface for your method :

  public interface MyInterface {
    public String buildDomClass();
  }

then the factory :

final class MyAdapter implements TypeAdapterFactory {

  @Override
  public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> tokenType) {
    final TypeAdapter<T> adapter = gson.getDelegateAdapter(this, tokenType);

    return new TypeAdapter<T>() {
      @Override
      public T read(JsonReader reader) throws IOException {
        return adapter.read(reader);
      }

      @Override
      public void write(JsonWriter writer, T value) throws IOException {
        JsonElement tree = adapter.toJsonTree(value);

        if (value instanceof MyInterface) {
          String dom = ((MyInterface) value).buildDomClass();
          JsonObject jo = (JsonObject) tree;
          jo.addProperty("dom", dom );
        }

        gson.getAdapter(JsonElement.class).write(writer, tree);
      }
    };
  }
}

Easy to understand, if the object you want to serialize implement the interface, you delegate the serializing, and then you add an extra property holding you DOM.

In case you don't know, you register a factory like this

Gson gson = new GsonBuilder().registerTypeAdapterFactory(new MyAdapter()).create();
like image 152
PomPom Avatar answered Oct 23 '22 17:10

PomPom