我正在使用带有 Java 的 Play Framework 1.2.4 并使用 JPA 来保存我的数据库对象。我有几个模型类要呈现为 JSON。但问题是我想自定义这些 JSON 响应并在呈现为 JSON 之前简化对象。
例如,假设我有一个名为 ComplexClass 的对象并具有属性 id、name、property1、...、propertyN。在 JSON 响应中,我只想呈现 id 和 name 字段。
这样做最优雅的方法是什么?编写自定义 Binder 对象或是否有简单的 JSON 映射,例如使用模板?
最佳答案
Play Framework 1.2.4 直接依赖于 gson
库,因此您可以使用它来呈现 JSON 字符串。您所要做的就是使用 gson 的 @Expose
注释。因此,在您的示例中,您将在 JSON 字符串中标记所需的字段,如下所示:
public class ComplexClass {
@Expose
public Long id;
@Expose
public String name;
...
}
然后在您的 Controller 中,您只需执行以下操作:
public static void someActionMethod() {
// get an instance of your ComplexClass here
ComplexClass complex = ...
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
String json = gson.toJson(complex);
renderJson(json);
}
参见文档 here .
如果 ComplexClass 实际上是一个 play.db.jpa.Model
并且因此 id
字段在父类中被抽象掉了,你不能把 @Expose
注释,然后你可以创建自己的 ExclusionStrategy跳过未使用 @Expose
注释且未称为 id
的字段。所以像这样(伪代码):
public final class ComplexClassExclusionStrategy implements ExclusionStrategy {
public boolean shouldSkipField(FieldAttributes attributes) {
if (name of field is "id") return false;
if (field is annotated with @Expose) return false;
return true;
}
然后 Controller 会稍微改变一下,看起来像这样:
GsonBuilder builder = new GsonBuilder();
ComplexClassExclusionStrategy strategy = new ComplexClassExclusionStrategy();
builder.setExclusionStrategies(strategy);
Gson gson = builder.create();
String json = gson.toJson(complex);
renderJson(json);
关于java - Play Framework : Rendering custom JSON objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9638529/