在Play中定制JSON序列化 [英] Customizing JSON serialization in Play

查看:112
本文介绍了在Play中定制JSON序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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实现了JsonSerializer< DateTime> {
public JsonElement serialize(SpecificClass src,Type typeOfSrc,JsonSerializationContext context){
String res =specialClass的特殊格式
return new JsonPrimitive(res);
}
}


I'm using renderJSON(Object) to return some objects as JSON values, and it's working fine except for one field. Is there an easy way to add in that one field without having to manually create the whole json template?

解决方案

Play uses GSON to build the JSON string. If your one field is a specific object type, then you can easily do this by providing a customised serialisation for that type. See the documentation here

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

However, if it is an Integer class for example, that you want to work in one way for one, and another way for another, then you may have a little more difficulty.

Example

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

这篇关于在Play中定制JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆