使用FlexJSON,這很容易。它允許您創建可以包含/排除所需字段的JSONSerializer。
查看this article的一些使用Play的例子!框架。
這裏有一個簡單的例子:
public ComplexClass {
public Long id;
public String name;
// And lots of other fields you don't want
public String toJsonString() {
// Include id & name, exclude all others.
JSONSerializer ser = new JSONSerializer().include(
"id",
"name",
).exclude("*");
return ser.serialize(this);
}
}
你可以把它添加到您的dependencies.yml像這樣:
require:
- play
- net.sf.flexjson -> flexjson 2.1
我最常做的是寫模式,實現的接口我可以在控制器中調用renderJSON(someModel.toJSONString())
。
Link to official website
編輯:對列表/收藏
好吧,當你開始序列化列表中,您可能會得到一些意想不到的結果額外的例子。這是因爲評估順序很重要。第一個include()
或exclude()
優先於以下幾個。
下面是序列化父實體的子對象(OneToMany關係)的示例。
JSONSerializer ser = new JSONSerializer();
// Exclude these standard fields from childs
ser.exclude(
"*.persistent",
"*.class",
"*.entityId"
);
// Include childs and all its other fields
ser.include(
"childs",
"childs.*"
);
// Exclude everything else
ser.exclude("*");
String data = ser.serialize(parent);
的*
是順便說一個通配符。這篇文檔很好地解釋了它:
排除*.class
將匹配任何路徑深度。因此,如果flexjson將該字段序列化爲「foo.bar.class」的路徑,則*.class
中的*
將與foo.bar匹配。
非常感謝你爲你的優雅答案。我會試一試。 FlexJson聽起來很好用,因爲在相同的數據上創建多個視圖要容易得多。 – huzeyfe 2012-03-12 09:13:55
順便說一句,(如果可能的話)你能提供一些關於你的接口細節的細節,這樣我也可以用這種方式在控制器中使用,因爲我也需要序列化對象列表。 – huzeyfe 2012-03-12 12:24:49
更新了一個列表示例:) – maartencls 2012-03-13 12:58:56