在Play中自定义JSON序列化

Bra*_*ace 1 serialization json gson playframework

我正在使用renderJSON(Object)一些对象作为JSON值返回,除了一个字段外它工作正常.是否有一种简单的方法来添加一个字段而无需手动创建整个json模板?

Cod*_*nci 6

Play使用GSON构建JSON字符串.如果您的一个字段是特定的对象类型,那么您可以通过为该类型提供自定义序列化来轻松完成此操作.请参阅此处的文档

http://sites.google.com/site/gson/gson-user-guide#TOC-Custom-Serialization-and-Deserializ

但是,如果它是一个Integer类,你希望以一种方式为一种方式工作,而另一种方式为另一种方式工作,那么你可能会遇到一些困难.

GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(SpecificClass.class, new MySerializer());

private class MySerializer implements JsonSerializer<DateTime> {
  public JsonElement serialize(SpecificClass src, Type typeOfSrc, JsonSerializationContext context) {
    String res = "special format of specificClass"
    return new JsonPrimitive(res);
  }
}
Run Code Online (Sandbox Code Playgroud)