使用Gson和抽象类

时间:2013-04-14 14:30:54

标签: java object gson abstract-class

我正在尝试使用GSON在客户端和服务器之间交换消息。

问题如下:

我有这个结构:

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

然后,对象内容可以是各种类。

我找到了2个教程herehere,但没有一个能解决问题。

EDIT1:

类消息就是这个:


public class Mensagem
{
private TipoMensagem    type;

    private Conteudo        conteudo;

    private Cliente         autor;
    private Cliente         destino;    // null -> to all(broadcast)
}

内容就是这个:

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;
}    
} 

来自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;

}



}

最后我做的是:“String strObject = new Gson()。toJson(mensage);”它的工作原理,但在反序列化时,它不会因为它始终假定它来自Content class

3 个答案:

答案 0 :(得分:9)

我终于解决了!

    // 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);

请注意:“registerTypeAdapter( AbstractClass.class ,新的InterfaceAdapter());”

by AbstractClass.class 我的意思是你在我的案例中实现的类是Conteúdo,可能是ConteudoTweet或ConteudoUserSystem等等......

InterfaceAdapter 的实现是:

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;
    }

}

这个InterfaceAdapter是通用的,因此它应该可以正常工作......

就是这样!

答案 1 :(得分:1)

你应该看看我在这里回答的类似问题: https://stackoverflow.com/a/22081826/3315914

您需要使用Gson's RuntimeTypeAdapterFactory

注册基类和所有子类以使其工作。

答案 2 :(得分:0)

这是我对Sub类型序列化的看法。 (github repo here)

// GsonSerializer.java
package com.rathnas.main;

import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
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;
import com.rathnas.vo.Thing;
import com.rathnas.vo.sub.Animal;
import com.rathnas.vo.sub.Bird;
import com.rathnas.vo.sub.nested.Barking;
import com.rathnas.vo.sub.nested.Chirping;
import com.rathnas.vo.sub.nested.NoiseType;

public class GsonSerializer {
    public static void main(String[] args) {
        GsonBuilder builder = new GsonBuilder().registerTypeAdapter(Thing.class, new ThingSerializer<Thing>()).registerTypeAdapter(NoiseType.class, new ThingSerializer<NoiseType>());
        builder.setPrettyPrinting();
        Gson gson = builder.create();
        Animal thing = God.createDog();
        String tmp = gson.toJson(thing, Thing.class); // Note: StackoverflowError, if you do gson.toJson(thing)
        System.out.println("Ser Dog: " + tmp);
        System.out.println("Des Dog: " + gson.fromJson(tmp, Thing.class));
        Bird thing2 = God.createBird();
        tmp = gson.toJson(thing2, Thing.class);
        System.out.println("\n\n\nSer Bird: " + tmp);
        System.out.println("Des Bird: " + gson.fromJson(tmp, Thing.class));
    }
}

class ThingSerializer<T> implements JsonSerializer<T>, JsonDeserializer<T> {
    private static final String TYPE = "type";

    public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonObject jsonObj = json.getAsJsonObject();
        String className = jsonObj.get(TYPE).getAsString();
        try {
            return context.deserialize(json, Class.forName(className));
        } catch (ClassNotFoundException e) {
            throw new JsonParseException(e);
        }
    }
    public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context) {
        JsonElement jsonEle = context.serialize(src, src.getClass());
        jsonEle.getAsJsonObject().addProperty(TYPE, src.getClass().getCanonicalName());
        return jsonEle;
    }
}

class God {
    public static Animal createDog() {
        Animal thing = new Animal();
        thing.setName("Dog");
        thing.setLegs(4);
        thing.setWings(0);
        thing.setNoise(new Barking());
        return thing;
    }
    public static Bird createBird() {
        Bird thing = new Bird();
        thing.setName("Bird");
        thing.setLegs(1);
        thing.setWings(2);
        thing.setNoise(new Chirping());
        return thing;
    }
}
// Thing.java
public abstract class Thing {
    private String name;
    private NoiseType noise;
    ..
}

// Animal.java
public class Animal extends Thing implements iThing {
    private Integer legs;
    private Integer wings;
    ..
}
// Bird.java
public class Bird extends Thing implements iThing {
    private Integer legs;
    private Integer wings;
    ..
}
// NoiseType.java
public abstract class NoiseType {..}
// Chirping.java
public class Chirping extends NoiseType {..}
// Barking.java
public class Barking extends NoiseType {..}

输出

Ser Dog: {
  "legs": 4,
  "wings": 0,
  "name": "Dog",
  "noise": {
    "noise": "barking",
    "type": "com.rathnas.vo.sub.nested.Barking"
  },
  "type": "com.rathnas.vo.sub.Animal"
}
Des Dog: Animal [legs=4, wings=0, noise=NestedAbstractClass [noise=barking]]

Ser Bird: {
  "legs": 1,
  "wings": 2,
  "name": "Bird",
  "noise": {
    "noise": "chirping",
    "type": "com.rathnas.vo.sub.nested.Chirping"
  },
  "type": "com.rathnas.vo.sub.Bird"
}
Des Bird: Bird [legs=1, wings=2, noise=NestedAbstractClass [noise=chirping]]