在 Play 中自定义 JSON 序列化 [英] Customizing JSON serialization in Play
问题描述
我正在使用 renderJSON(Object)
将一些对象作为 JSON 值返回,除了一个字段外,它工作正常.是否有一种简单的方法可以添加该字段而无需手动创建整个 json 模板?
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 使用 GSON 来构建 JSON 字符串.如果您的一个字段是特定的对象类型,那么您可以通过为该类型提供自定义序列化来轻松完成此操作.请参阅此处的文档
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
但是,例如,如果它是一个 Integer 类,您想以一种方式为一种方式工作,而另一种方式则为另一种方式工作,那么您可能会遇到更多困难.
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.
示例
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屋!