使用Struts2-Json插件时出现Json序列化问题

时间:2015-05-26 09:27:50

标签: json serialization struts2 struts2-json-plugin

我有一个包含3个属性的动作类。我正在使用Struts2-Json插件来序列化动作类。我可以按照我的期望序列化 String selectedCompany

问题

ArrayList<Person>属性序列化为空值。我似乎无法找到我犯错的地方。

Json_Response:

enter image description here

行动类:

package json;

import java.util.ArrayList;

import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

import dao.DataAccess;

public class Json extends ActionSupport implements Preparable {

    private static final long serialVersionUID = -8415223624346993447L;
    private ArrayList<String> list; 
    private String selectedCompany = "Buhin Engineers";
    private ArrayList<Person> people;

    public ArrayList<String> getList() {
        return list;
    }
    public void setList(ArrayList<String> list) {
        this.list = list;
    }
    public String getSelectedCompany() {
        return selectedCompany;
    }
    public void setSelectedCompany(String selectedCompany) {
        this.selectedCompany = selectedCompany;
    }
    public ArrayList<Person> getPeople() {
        return people;
    }
    public void setPeople(ArrayList<Person> people) {
        this.people = people;
    }
    public String execute(){
        list = new ArrayList<String>();
        list.add("Yamaha");
        list.add("Hero Honda");
        return SUCCESS;
    }
    @Override
    public void prepare() throws Exception {
        // TODO Auto-generated method stub
        populatePeople();
    }
    private void populatePeople() {
        // TODO Auto-generated method stub
        DataAccess da = new DataAccess();
        setPeople(da.retrievePeople());

    }
}

struts.xml中

<?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>
        <constant name="struts.devMode" value="true" />
        <package name="default" namespace="/" extends="json-default">
            <action name="Json" class="json.Json">
                <result type="json">
                    <param name="includeProperties">selectedCompany,people,list</param>
                </result>
            </action>
        </package>
    </struts>

1 个答案:

答案 0 :(得分:2)

List作为数组发布,因此您需要定义要包含的数组。像

people\[\d+\]\..*,list\[\d+\]\..* 

如果List是对象类型(而不是简单String),您可以将结果范围缩小到以下所选属性:

employee\[\d+\]\.lName,employee\[\d+\]\.fName,

如果List个对象有内部对象,你可以这样做:

//The employee\[\d+\]\.address.addressline1 is not enough !!
//May be one can suggest better idea here :)
employee\[\d+\]\.address,employee\[\d+\]\.address.addressline1