Ashish の回答に追加するには、struts2-json-plugin を追加した後です。
私は可能であれば struts2-conventions-plugin を使用するのが好きです。そのため、struts.xml にはほとんど含まれておらず、代わりに主に注釈を使用することを好みます。
規則を使用するときにアクションが json を返すようにするには、次の 2 つの手順があります。1) アクションで json-default パッケージを使用する、2) json の結果タイプを持つアクションを定義する。
JSON アノテーションの例
package org.test.action;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
@ParentPackage("json-default")
@Result(type = "json")
public class JsonTest extends ActionSupport{
private String name = "Hello World";
private String language = "Java, I mean English";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
}
値がプリミティブよりも複雑で、返された json をプルーニングしたい場合や、複数のアクションを単一のクラスに入れたい場合があります (複雑な構造が返され、特定の方法でプルーニングすることで、クライアントは簡単です)。これを行うには、包含パラメーターまたは除外パラメーターを使用します。
除外言語の例
上記の結果の注釈を次のように変更します。
@Result(type = "json", params = {
"excludeProperties",
"language"})
上記を実現する別の方法は、必要なプロパティを明示的に指定することです。
@Result(type = "json", params = {
"includeProperties",
"name"})
例 除外パラメーターでのワイルド カードの使用
アクション コードが提供されていないため、複雑なオブジェクトのトリミングに適しています
@Result(type = "json", params = {
"excludeProperties",
"punches.*.punchesCollection, *.punchesCollection.*"})
プラグインを使用すると、xml または注釈メソッドよりも簡単にするのがかなり難しいことがわかります。