如何在Gson

时间:2017-03-26 17:51:22

标签: java json serialization gson spark-java

我使用下面的方法(来自spark-java framework的方法)从DB返回数据:

get("/data_on_page_load", "application/json", (Request request, Response response) -> {
    List<Post> list = Post.findAll(); // NEED TO SERIALIZE THE RESPONSE
    System.out.println("list is  " + list);
    return (list);
}, new JsonTransformer());

从DB返回的数据:

 [Model: com.soul.seeker.models.Post, table: 'post', attributes: {created_at=2017-03-26 04:06:35.0, details=aaa, id=36, title=Eventsa, url=eventsa, userImage=assets/img/spiritual-icon4.png, username=null}]

Post.findAll(); 是来自http://javalite.io/record_selection#finding-all-records的方法以获取所有记录

Model: com.soul.seeker.models.Post是下面的POJO类:

public class Post extends Model{
   private String title;
   private String details;
   private String username;
   private String userImage;
   private String url;
   private List categories;

   //Getters and Setters removed for brevity
}

我正在尝试使用GSON TypeTokenTypeAdapter

序列化输出

ClassTypeAdapterFactory:

public class ClassTypeAdapterFactory implements TypeAdapterFactory {

    @Override
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {

        if(!Class.class.isAssignableFrom(typeToken.getRawType())) {
            return null;
        }

        return (TypeAdapter<T>) new ClassTypeAdapter();
    }
}

ClassTypeAdapter:

public class ClassTypeAdapter extends TypeAdapter<Class<?>> {
    @Override
    public void write(JsonWriter jsonWriter, Class<?> clazz) throws IOException {
        if(clazz == null){
            jsonWriter.nullValue();
            return;
        }
        jsonWriter.value(clazz.getName());
    }

    @Override
    public Class<?> read(JsonReader jsonReader) throws IOException {
        if (jsonReader.peek() == JsonToken.NULL) {
            jsonReader.nextNull();
            return null;
        }
        Class<?> clazz = null;
        try {
            clazz = Class.forName(jsonReader.nextString());
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        return clazz;
    }
}

我在这里使用JsonTransformer来实现spark-java ResponseTransformer interface

中的ResponseTransformer
public class JsonTransformer implements ResponseTransformer {

    private Gson gson = new Gson();

    @Override
    public String render(Object model) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gson = gsonBuilder.registerTypeAdapterFactory(new ClassTypeAdapterFactory()).create();
        return gson.toJson(model);
    }
}

现在问题是json out put还包含序列化类而不是只返回pojo类的List对象。我不熟悉Java&amp; Gson序列化。

任何人都可以帮助实现TypeAdapter只返回List对象吗?像这样的例子:

Type listOfTestObject = new TypeToken<List<TestObject>>(){}.getType();
String s = gson.toJson(list, listOfTestObject);
List<TestObject> list2 = gson.fromJson(s, listOfTestObject);

1 个答案:

答案 0 :(得分:0)

我认为您不需要键入Response Transformer,您可以直接使用新的Gson对象,就像response transformer documentation的最后一个片段一样。它最终会像这样:

    get("/data_on_page_load", (req, res) -> {
        res.type("application/json; charset=UTF-8");
        List<Post> list = Post.findAll();
        System.out.println("list is  " + list);
        return list;
    }, new Gson()::toJson);