Struts2的JSON返回值与Json插件
返回json需要jsonplugin-0[1].25的jar包
然后我们的配置文件中需要继承json-default
Java 代码
1. <?xml version="1.0" encoding="UTF-8" ?>
2. <!DOCTYPE struts PUBLIC
3. "-//Apache Software Foundation//DTD Struts Configuration 2.0//
EN"
4. "http://struts.apache.org/dtds/struts-2.0.dtd">
5.
6. <struts>
7.
8. <package name="com.act ion.testJson" extends="json-default" nam
espace="/" >
9. <action name="jsonUser" class="com.act ion.testJson.JsonAction
" method="testUser">
10. <result type="json"/>
11. </action>
12. <!-- Add actions here -->
13. </package>
14.</struts>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="com.act ion.testJson" extends="json-default"
namespace="/" >
<action name="jsonUser" class="com.act ion.testJson.JsonAction"
method="testUser">
<result type="json"/>
</action>
<!-- Add actions here -->
</package>
</struts>
然后我们的Action 中需要返回的json 信息需要加上注解
Java 代码
1. //pizza
2. package com.action.testJson;
3.
4. import java.util.ArrayList;
5. import java.util.List;
6.
7. import com.googlecode.jsonplugin.annotations.JSON;
8. import com.opensymphony.xwork2.ActionSupport;
9.
10.public class JsonAction extends ActionSupport {
11.
12. private static final long serialVersionUID = -
4082165361641669835L;
13.
14. Users user=new Users();
15. List userList=new ArrayList();
16.
17.
18. public String testUser(){
19. System.out.println("in the json Acton");
20. userInit();
21. userList.add(user);
22. return SUCCESS;
23. }
24.
25. public void userInit(){
26. user.setAge(1);
27. user.setName(" 张泽峰");
28. user.setPassword("nofengPassword");
29. }
30.
31. @JSON(name="userString")
32. public Users getUser() {
33. return user;
34. }
35.
36. @JSON(name="userList")
37. public List getUserList() {
38. return userList;
39. }
40.
41. public void setUser(Users user) {
42. this.user = user;
43. }
44.
45. public void setUserList(List userList) {
46. this.userList = userList;
47. }
48.
49.
50.}
JSON Plugin
的说明
Edit Page Browse Space Add Page Add News
Added by Musachy Barroso, last edited by ghostroller on Jul 04, 2008 (vie w change) SHOW COMMENT
Name JSON Plugin
Publisher Musachy Barroso
License Open Source (ASL2)
Version 0.30
Compatibility Struts 2.0.6 or later
Homepage http://code.google.com/p/jsonplugin/
Download http://code.google.com/p/jsonplugin/downloads/list
Overview
The JSON plugin provides a "json" result type that serializes actions into JSON. The serializa tion
process is recursive, meaning that the whole object graph, starting on the action class (base
class not included) will be serialized (root object can be customized using the "root" attribute).
If the interceptor is used, the action will be populated from the JSON content in the request,
these are the rules of the interceptor:
1. The "content-type" must be "application/json"
2. The JSON content must be well formed, see json.org for grammar.
3. Action must have a public "setter" method for fields that must be populated.
4. Supported types for population are: Primitives (int,long...String), Date, List, Map,
Primitive Arrays, Other class (more on this later), and Array of Other class.
5. Any object in JSON, that is to be populated inside a list, or a map, will be of type Map
(mapping from properties to values), any whole number will be of type Long, any
decimal number will be of type Double, and any array of type List.
Given this JSON string:
{
"doubleValue": 10.10,
"nestedBean": {
"name": "Mr Bean"
},
"list": ["A", 10, 20.20, {
"firstName": "El Zorro"
}],
"array": [10, 20]
}
The action must have a "setDoubleValue" method, taking either a "float" or a "double" argument
(the interceptor will convert the value to the right one). There must be a "setNestedBean"
whose argument type can be any class, that has a "setName" method taking as argument an
"String". There must be a "setList" method that takes a "List" as argument, that list will contain:
"A" (String), 10 (Long), 20.20 (Double), Map ("firstName" -> "El Zorro"). The "setArray"
method can take as parameter either a "List", or any numeric array.
Rating?
• 1
• 2
• 3
• 4
• 5
Installation
This plugin can be installed by copying the plugin jar into your application's /WEB-INF/lib
directory. No other files need to be copied or created.
To use maven, add this to your pom:
<dependencies>
...
<dependency>
<groupId>com.googlecode</groupId>
<artifactId>jsonplugin</artifactId>
<version>0.26</version>
</dependency>
...
</dependencies>
<repository>
<id>Maven Plugin Repository</id>
<url>http://struts2plugin-mavenrepo.
googlecode.com/svn/trunk/</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</repository>
Customizing Serialization and Deserialization
Use the JSON annotation to customize the serializa tion/deserializa tion process. Available JSON
annotation fields:
Name Description Default Value Serialization Deserialization
name Customize field name empty yes no
serialize
Include in
serializa tion
true yes no
deserialize
Include in
deserializa tion
true no yes
Excluding properties
A comma-delimited list of regular expressions can be passed to the JSON Result and Interceptor,
properties matching any of these regular expressions will be ignored on the serializa tion process:
<!-- Result fragment -->
<result type="json">
<param name="excludeProperties">
login.password,
studentList.*\.sin
</param>
</result>
<!-- Interceptor fragment -->
<interceptor-ref name="json">
<param name="enableSMD">true</param>
<param name="excludeProperties">
login.password,
studentList.*\.sin
</param>
</interceptor-ref>
Including properties
A comma-delimited list of regular expressions can be passed to the JSON Result to restrict
which properties will be serialized. ONLY properties matching any of these regular expressions
will be included in the serialized output.
<!-- Result fragment -->
<result type="json">
<param name="includeProperties">
^entries\[\d+\]\.clientNumber,
format
Format used to
format/parse a Date
field
"yyyy-MM-dd'T'HH:mm:ss" yes yes
Note
Exclude property expressions take precedence over include property
expressions. That is, if you use include and exclude property expressions
on the same result, include property expressions will not be applied if an
exclude exclude property expression matches a property first.
^entries\[\d+\]\.scheduleNumber,
^entries\[\d+\]\.createUserId
</param>
</result>
Root Object
Use the "root" attribute(OGNL expression) to specify the root object to be serialized.
<result type="json">
<param name="root">
person.job
</param>
</result>
The "root" attribute(OGNL expression) can also be used on the interceptor to specify the object
that must be populated, make sure this object is not null.
<interceptor-ref name="json">
<param name="root">bean1.bean2</param>
</interceptor-ref>
Wrap with Comments
If the "wrapWithC omments" (false by default) attribute is set to true, the generated JSON is
wrapped with comments like:
/* {
"doubleVal": 10.10,
"nestedBean": {
"name": "Mr Bean"
},
"list": ["A", 10, 20.20, {
"firstName": "El Zorro"
}],
"array": [10, 20]
} */
wrapWithComments can turn safe JSON text into dangerous text. For
example,
["*/ alert('XSS'); /*"]
Thanks to Douglas Crockford for the tip!
This can be used to avoid potential Javascript Hijacks . To strip those comments use:
var responseObject = eval("("+data.substring(data.indexOf("\/\*")+2,
data.lastIndexOf("\*\/"))+")");
Base Classes
By default properties defined on base classes of the "root" object won't be serialized, to serialize
properties in all base classes (up to Object) set "ignoreHierarchy" to false in the JSON result:
<result type="json">
<param name="ignoreHierarchy">false</param>
</result>
Enumerations
By default, an Enum is serialized as a name=value pair where value = name().
public enum AnEnum {
ValueA,
ValueB
}
JSON: "myEnum":"ValueA"
Use the "enumAsBean" result parameter to serialize Enum's as a bean with a special property
_name with value name(). All properties of the enum are also serialized.
public enum AnEnum {
ValueA("A"),
ValueB("B");
private String val;
public AnEnum(val) {
this.val = val;
}
public getVal() {
return val;
}
}
JSON: myEnum: { "_name": "ValueA", "val": "A" }
Enable this parameter through struts.xml:
<result type="json">
<param name="enumAsBean">true</param>
</result>
Compressing the output.
Set the enableGZIP attribute to true to gzip the generated json response. The request must
include "gzip " in the "Accept-Encoding" header for this to work.
<result type="json">
<param name="enableGZIP" >true</param>
</result>
Example
Setup Action
This simple action has some fields:
Example:
import java.util.HashMap;
import java.util.Map;
import com.opensymphony.xwork2.Action;
public class JSONExample {
private String field1 = "str";
private int[] ints = {10, 20};
private Map map = new HashMap();
private String customName = "custom";
//'transient' fields are not serialized
private transient String field2;
//fields without getter method are not serialized
private String field3;
public String execute() {
map.put("John", "Galt");
return Action.SUCCESS;
}
public String getField1() {
return field1;
}
public void setField1(String field1) {
this.field1 = field1;
}
public int[] getInts() {
return ints;
}
public void setInts(int[] ints) {
this.ints = ints;
}
public Map getMap() {
return map;
}
public void setMap(Map map) {
this.map = map;
}
@JSON(name="newName")
public String getCustomName() {
return this.customName;
}
}
Write the mapping for the action
1. Add the map inside a package that extends "json-default"
2. Add a result of type "json"
Example:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="example" extends="json-default">
<action name="JSONExample" class="example.JSONExample">
<result type="json"/>
</action>
</package>
</struts>
JSON example output
{
"field1" : "str",
"ints": [10, 20],
"map": {
"John":"Galt"
},
"newName": "custom"
}
posted on 2011-02-18 16:45 Eason Jiang 阅读(16562) 评论(0) 编辑 收藏 举报