JSON 插件提供了一个 "json" 结果类型来把 action 序列化成 JSON. 这一序列化的过程是递归的, 意即整个对象图,从 action 类开始 (未包括基类) 将会被序列化 (可以用 "root" 属性来指定自己的根对象). 如果使用了 json 拦截器, action 将可通过请求中的 JSON 内容组装出来, 该拦截器遵循以下几条规则:
给定下面的 JSON 字符串:
action 中必须有一个 "setDoubleValue" 方法, 参数为 "float" 或者 "double"(拦截器将会把值转换为相应的类型). 还必须有一个 "setNestedBean" 方法,它的参数类型可以为任何类类型, 其中含有参数为 "String" 的 "setName" 方法. 还必须有一个参数为 "List" 的 "setList" 方法, 这个 List 中将会包含: "A" (String), 10 (Long), 20.20 (Double), Map ("firstName" -> "El Zorro"). "setArray" 方法可以是 "List", 或任何数字类型数组作参数的.{ "doubleValue": 10.10, "nestedBean": { "name": "Mr Bean" }, "list": ["A", 10, 20.20, { "firstName": "El Zorro" }], "array": [10, 20] }
序列化你的对象成 javascript 的 JSON, 参考 json2 |
本插件可通过把插件 jar 包到你的应用的 /WEB-INF/lib 目录来完成安装. 没有别的文件需要拷贝或被创建.
使用 maven 的话, 加入下列到你的 pom 中:
ncies> ... ... org.apache.struts struts2-json-plugin STRUTS_VERSION
使用 JSON 注解来达到定制序列化和反序列化过程. 可用的 JSON 注解如下:
名称 | 描述 | 默认值 | 序列化 | 反序列化 |
---|---|---|---|---|
name | 定制字段名 | empty | yes | no |
serialize | 标识为可被序列化 | true | yes | no |
deserialize | 标识为可被反序列化 | true | no | yes |
format | 用于格式化或解析 Date 字段的格式 | "yyyy-MM-dd'T'HH:mm:ss" | yes | yes |
排除属性
逗号分隔的正则表达式列表可传递给 JSON Result 和 Interceptor(拦截器), 被任何 一个正则表达式匹配的属性将会在序列化过程时忽略掉:
包含属性login.password, studentList.*\.sin true login.password, studentList.*\.sin
逗号分隔的正则表达式列表可被传递给 JSON Result, 用于限制哪些属性可用于序列化. 只有当能够匹配任何一个正则表达式的属性才会包含在序列化输出中.
注: 排除属性表达式优先于包含属性的表达式. 那就是说, 如果包含和排除表达式应用于同一个结果, 包含表达式对于被排除表达式匹配到的属性是不起作用的. |
根对象^entries\[\d+\]\.clientNumber, ^entries\[\d+\]\.scheduleNumber, ^entries\[\d+\]\.createUserId
使用 "root" 属性(OGNL 表达式) 指定被用于序列化的根对象.
person.job
"root" 属性(OGNL 表达式) 也可以用于拦截器来指定被组装的对象, 确保这个对象不会是 null.
包装bean1.bean2
可能会有某些原因,你想要用些文本对 JSON 输出包装一下, 像用注释包裹, 加上前缀, 或使用文件上载让结果显示在 textarea 之中. 用 wrapPrefix 在开始处加上内容,wrapPostfix 添加内容在尾端. 这两个参数优先使用,而 "wrapWithComments" 和 "prefix" 自从 0.34 后就不推荐使用. 例子:
进行注释:
/* */
添加前缀:
{}&&
包裹上传的文件内容: