Using the Gson and Abstract Classes

I am trying to exchange messages between client and server using GSON.

The problem is this:

I have this structure:

public class Message { private TypeOfContent type; // It a enum private Content content; .... } 

Then the contents of the object can be a different set of classes.

I found 2 tutorials here and here , but none of them solves the problem.

Edit1:

The class message is as follows:


 public class Mensagem { private TipoMensagem type; private Conteudo conteudo; private Cliente autor; private Cliente destino; // null -> to all(broadcast) } 

And the content is:

 public class Conteudo { protected TipoConteudo typeConteudo; protected String texto; protected Posicao posicao; public Conteudo(TipoConteudo typeConteudo, String texto, Posicao posicao) { this.texto = texto; this.posicao = posicao; this.typeConteudo = typeConteudo; } } 

And an example of an extended class from contedo:

 public class ConteudoTweet extends Conteudo { protected String pathImagem; public ConteudoTweet(TipoConteudo typeConteudo, String tweet, Posicao location, String picturePath) { super(typeConteudo,tweet, location); this.pathImagem = picturePath; } } 

Finally, what I'm doing: "String strObject = new Gson (). ToJson (mensage);" which works, but when deserializing it does not, because it always assumes that it is from the Content class

+6
source share
2 answers

I finally decided it!

  // GSON GsonBuilder gsonBilder = new GsonBuilder(); gsonBilder.registerTypeAdapter(Conteudo.class, new InterfaceAdapter<Conteudo>()); gsonBilder.setPrettyPrinting(); Gson gson =gsonBilder.create(); String str2send = gson.toJson(message); Mensagem msg_recv = gson.fromJson(str2send,Mensagem.class); 

Please note that: "registerTypeAdapter ( AbstractClass.class , new interface InterfaceAdapter ());

AbstractClass.class I mean the class that you implement in my case is Conteúdo, which can be ConteudoTweet or ConteudoUserSystem and so on ...

InterfaceAdapter implementation:

 import java.lang.reflect.Type; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public class InterfaceAdapter<T> implements JsonSerializer<T>, JsonDeserializer<T> { @Override public final JsonElement serialize(final T object, final Type interfaceType, final JsonSerializationContext context) { final JsonObject member = new JsonObject(); member.addProperty("type", object.getClass().getName()); member.add("data", context.serialize(object)); return member; } @Override public final T deserialize(final JsonElement elem, final Type interfaceType, final JsonDeserializationContext context) throws JsonParseException { final JsonObject member = (JsonObject) elem; final JsonElement typeString = get(member, "type"); final JsonElement data = get(member, "data"); final Type actualType = typeForName(typeString); return context.deserialize(data, actualType); } private Type typeForName(final JsonElement typeElem) { try { return Class.forName(typeElem.getAsString()); } catch (ClassNotFoundException e) { throw new JsonParseException(e); } } private JsonElement get(final JsonObject wrapper, final String memberName) { final JsonElement elem = wrapper.get(memberName); if (elem == null) { throw new JsonParseException( "no '" + memberName + "' member found in json file."); } return elem; } } 

And this InterfaceAdapter is generic, so it should work as a whole ...

What is it!

+8
source

You should look at a similar question that I answered here: fooobar.com/questions/68996 / ...

You need to use the Gson RuntimeTypeAdapterFactory

And register the base class and all the child classes to make it work.

+1
source

All Articles