Struts2-Json插件的使用


Struts2-Json
插件的使用

参考地址:http://struts.apache.org/release/2.3.x/docs/json-plugin.html

 

The JSON plugin provides a "json" result type that serializes actions into JSON. The serialization 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:

The "content-type" must be "application/json"

The JSON content must be well formed, see json.org for grammar.

Action must have a public "setter" method for fields that must be populated.

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.

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.

JSON插件提供一种叫做“json”返回类型,来将action序列化成JSON格式。序列化过程是递归的,这意味着整个对象图(从action开始,父类不会被序列化)都会被序列化(根对象可以通过“root”属性来自定义)。如果设置了拦截器,action将被请求中的JSON填充,下面是拦截器的规则:

1.请求的"content-type"必须为"application/json"

2.JSON内容必须是格式良好的,语法参见json.org

3.Action中被填充的属性必须要有一个setter方法

4.可以被填充的类型包括:原生类型(),DateList, Map, 原生数组,其他class,和其他class的数组

5.被填充到一个list或者一个map中的任何JSON对象,将是Map类型的(将属性映射为值),任何数值将被认为是long类型的,任何小数数值被认为是double类型,任何数组被认为是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 "float" 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.

action必须要有一个"setDoubleValue"方法,来接收一个"float" 或者参数"float" 参数(拦截器将值转换转换为合适的类型)。还必须要有一个"setNestedBean" 方法来设置对象,这个对象还必须要有一个"setName"方法参数类型为String。还必须要有一个"setList"方法来接收一个"List" 作为参数,这个列表将包含: "A" (String), 10 (Long), 20.20 (Double), Map ("firstName" -> "El Zorro"). "setArray" 方法可以接收一个"List"或者数字数组。

Use the JSON annotation to customize the serialization/deserialization process. Available JSON annotation fields:

Name

Description

Default Value

Serialization

Deserialization

name

Customize field name

empty

yes

no

serialize

Include in serialization

true

yes

no

deserialize

Include in deserialization

true

no

yes

format

Format used to format/parse a Date field

"yyyy-MM-dd'T'HH:mm:ss"

yes

yes

 

可以使用JSON注解来自定义序列化/反序列化的过程。可使用的JSON注解有:

名称

描述

默认值

序列化

反序列化

name

自定义字段的名称

empty

yes

no

serialize

包含到序列化中

true

yes

no

deserialize

包含到反序列化中

true

no

yes

format

Format被用来格式化/解析一个Date字段

"yyyy-MM-dd'T'HH:mm:ss"

yes

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 serialization 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.

 

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.

<!-- Result fragment -->

<result type="json">

  <param name="includeProperties">

    ^entries\[\d+\]\.clientNumber,

    ^entries\[\d+\]\.scheduleNumber,

    ^entries\[\d+\]\.createUserId

  </param>

</result>

 

 

排除属性

一个以逗号分隔的正则表达式列表,可以传递给JSON结果和拦截器,任何符合正则表达式的属性将在序列化过程中被忽略:

<!-- 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>

 

包含属性

一个以逗号分隔的正则表达式列表将传递给JSON结果来限制哪些属性可以被序列化。任何只有符合正则表达式的属性会被包含在序列化输出中。

 

注意

排除属性表达式优先于包含属性表达式。也就是说,如果你使用了包含和排除属性表达式在同一个result上,且排除属性表达式匹配了一个属性,同时包含属性表达式也匹配这个属性,那么只会应用排除表达式。

<!-- Result fragment -->

<result type="json">

  <param name="includeProperties">

    ^entries\[\d+\]\.clientNumber,

    ^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>

根对象

使用"root"属性(OGNL表达式)来指定被序列化的根

<result type="json">

  <param name="root">

    person.job

  </param>

</result>

 

"root"属性(OGNL表达式)还可以为拦截器指定必须被的填充的对象,确保这个对象不为空。

<interceptor-ref name="json">

  <param name="root">bean1.bean2</param>

</interceptor-ref>

 

 

Wrapping

For several reasons you might want to wrap the JSON output with some text, like wrapping with comments, adding a prefix, or to use file uploads which require the result to be wrapped in a textarea. Use wrapPrefix to add content in the beginning and wrapPostfix to add content at the end. This settings take precedence over "wrapWithComments" and "prefix" which are deprecated from 0.34 on. Examples:
Wrap with comments:

<result type="json">

  <param name="wrapPrefix">/*</param>

  <param name="wrapSuffix">*/</param>

</result>

 

Add a prefix:

<result type="json">

  <param name="wrapPrefix">{}&&</param>

</result>

 

Wrap for file upload:

<result type="json">

  <param name="wrapPrefix"><![CDATA[<html><body><textarea>]]></param>

  <param name="wrapSuffix"><![CDATA[</textarea></body></html>]]></param>

</result>

 

 

包裹

出于某些原因,你可能想为JSON包裹一些文本,比如包裹注释,添加一个前缀,或者文件上传要求将结果包裹在一个文本域中。使用wrapPrefix 在结果之前添加文本,使用wrapPostfix 在结果之后添加文本。这些设置优先于"wrapWithComments" "prefix" 。例如:

包裹注释:

<result type="json">

  <param name="wrapPrefix">/*</param>

  <param name="wrapSuffix">*/</param>

</result>

添加前缀:

<result type="json">

  <param name="wrapPrefix">{}&&</param>

</result>

包裹文件上传:

<result type="json">

  <param name="wrapPrefix"><![CDATA[<html><body><textarea>]]></param>

  <param name="wrapSuffix"><![CDATA[</textarea></body></html>]]></param>

</result>

 

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>

基类

默认定义在根对象中的基类属性是不会被序列化的,为了能序列化所有基类的属性(直到Object)可以在JSON result中设置"ignoreHierarchy" false

<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>

 

枚举

默认,一个枚举可以被序列化为一个名值对,值为name()方法的返回值。

  public enum AnEnum {

     ValueA,

     ValueB

  }

 

  JSON:  "myEnum":"ValueA"

使用 "enumAsBean" result参数可以将枚举当做一个bean来序列化,使用一个特殊的属性_name和值name(),枚举的所有属性都将被序列化。

  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" }

 

可以通过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>

压缩输出结果.

设置enableGZIP 属性为true可以压缩输出的json结果。请求头部的"Accept-Encoding" 包含"gzip"才可以使其工作。

<result type="json">

  <param name="enableGZIP">true</param>

</result>

Preventing the browser from caching the response

Set noCache to true(false by default) to set the following headers in the response:

· Cache-Control: no-cache

· Expires: 0

· Pragma: No-cache

<result type="json">

  <param name="noCache">true</param>

</result>

禁止浏览器缓存响应

设置了noCache true(默认为false)就等效于在响应头部设置了如下参数:

· Cache-Control: no-cache

· Expires: 0

· Pragma: No-cache

<result type="json">

  <param name="noCache">true</param>

</result>

Excluding properties with null values

By default fields with null values are serialized like {property_name: null}. This can be prevented by setting excludeNullProperties to true.

<result type="json">

  <param name="excludeNullProperties">true</param>

</result>

排除属性值为空的属性

默认情况下,值为null的属性会序列化为这样{property_name: null}.可以通过设置excludeNullPropertiestrue来阻止。

<result type="json">

  <param name="excludeNullProperties">true</param>

</result>

Status and Error code

Use statusCode to set the status of the response:

<result type="json">

  <param name="statusCode">304</param>

</result>

 

And errorCode to send an error(the server might end up sending something to the client which is not the serialized JSON):

<result type="json">

  <param name="errorCode">404</param>

</result>

状态和错误码

使用statusCode 来设置响应的状态

<result type="json">

  <param name="statusCode">304</param>

</result>

errorCode 会发送一个错误(服务器可能会发送非序列化的JSON到客户端):

<result type="json">

  <param name="errorCode">404</param>

</result>

JSONP

To enable JSONP, set the parameter callbackParameter in either the JSON Result or the Interceptor. A parameter with that name will be read from the request, and it value will be used as the JSONP function. Assuming that a request is made with the parameter "callback"="exec":

<result type="json">

  <param name="callbackParameter">callback</param>

</result>

 

And that the serialized JSON is {name: 'El Zorro'}. Then the output will be: exec({name: 'El Zorro'})

JSONP

为了启用JSONP功能,可以设置callbackParameter 参数到JSON Result 或者拦截器上。请求参数上为那个值的值将被用作JSONP方法,假设请求参数为"callback"="exec":

<result type="json">

  <param name="callbackParameter">callback</param>

</result>

序列化的JSON{name: 'El Zorro'},那么输出结果会是:exec({name: 'El Zorro'})

Content Type

Content type will be set to application/json-rpc by default if SMD is being used, or application/json otherwise. Sometimes it is necessary to set the content type to something else, like when uploading files with Dojo and YUI. Use the contentType parameter in those cases.

<result type="json">

  <param name="contentType">text/html</param>

</result>

Content Type

如果SMD 被使用那么Content type将被默认设置为application/json-rpc,否则将被设置为application/json,有时content type将被设置为其他类型,如:当使用 Dojo YUI上传文件时。

<result type="json">

  <param name="contentType">text/html</param>

</result>

Encoding

User can define encoding per result or base on default assigned to struts.i18n.encoding. To define encoding for given result add encoding param as below:

<result type="json">

  <param name="encoding">UTF-8</param>

</result>

编码

用户可以定义每一次请求的编码或者基于默认struts.i18n.encoding设置的值,为了定义指定result的编码可以添加encoding 参数,如下:

<result type="json">

  <param name="encoding">UTF-8</param>

</result>

 

例子

设置Action

这个action有一些简单的字段:

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字段不被序列化

    private transient String field2;

 

    //没有getter方法的字段不被序列化

    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;

    }

}

 

为这个action编写映射

将这个映射添加到一个继承了"json-default"的包中

添加一个类型为"json"result

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 @ 2013-02-28 22:56  lmtoo  阅读(1980)  评论(2编辑  收藏  举报