在Java中序列化List以作为JSON发送

时间:2014-09-17 08:23:02

标签: java jquery json serialization

我正在尝试对我的数组进行serlialize,以便即使它包含一个元素也可以工作,这就是我所做的:

@GET
@XmlElement(name = "contentbean")
@Path("/retrieveContent")
@Produces(MediaType.APPLICATION_JSON)
public JSONObject retrieve(@QueryParam("username") String Username, @QueryParam("path") String Path) throws JSONException {
    ContentBean oContentBean = buildResult(Username, Path);
    List<ContentBean> lContentBeans = new ArrayList<ContentBean>();
    lContentBeans.add(oContentBean);


    JSONObject jsonObject = new JSONObject();
    jsonObject.append("lContentBeans", lContentBeans);

    return jsonObject;
}

但在客户端,我收到以下内容:

["[org.qcri.crosscloud.utils.ContentBean@7f29b922]"]

这基本上是我的对象的数组,但每个对象在结果中变成一个字符串。我需要得到这个:

{"ContentBean":[{"prop1":"val", "prop2":"val"}, {"prop1":"val", "prop2":"val"} ]}

有什么想法吗?

谢谢,

更新1

采用了J.Lucky的回答,但现在得到的例外情况如下:

org.codehaus.jackson.map.JsonMappingException: No serializer found for class org.qcri.crosscloud.utils.ACLBean and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: java.util.ArrayList[0]->org.qcri.crosscloud.utils.ContentBean["acl"])

更新2

这是我的ContentBean

public static ContentBean buildResult(String sUsername, String sPath){

        //Scenario of retrieving an element that is a Directory (so no ACL)
        AttributesBean aB = new AttributesBean();
        aB.setName("profile/"); //From request
        aB.setType(false);  //Hard coded for testing purposes
        aB.setSize(0.2);   //Hard coded for testing purposes
        aB.setLastModified(new Date());

        ACLBean aclB = new ACLBean();
        RDFBean rdfB = new RDFBean();

        ContentBean cB = new ContentBean();
        cB.setUsername(sUsername); //From request
        cB.setAttributes(aB);
        cB.setACL(aclB);
        cB.setRDF(rdfB);

        return cB;
    }

ContentBean类:

@XmlRootElement 
public class ContentBean {

    private String username;
    private AttributesBean attributes;
    private RDFBean rdf;
    private ACLBean acl;

    /**
     * @return the attributes
     */
    public AttributesBean getAttributes() {
        return attributes;
    }

    /**
     * @param attributes the attributes to set
     */
    public void setAttributes(AttributesBean attributes) {
        this.attributes = attributes;
    }

    /**
     * @return the rdf
     */
    public RDFBean getRDF() {
        return rdf;
    }

    /**
     * @param rdf the rdf to set
     */
    public void setRDF(RDFBean rdf) {
        this.rdf = rdf;
    }

    /**
     * @return the acl
     */
    public ACLBean getACL() {
        return acl;
    }

    /**
     * @param acl the acl to set
     */
    public void setACL(ACLBean acl) {
        this.acl = acl;
    }

    /**
     * @return the username
     */
    public String getUsername() {
        return username;
    }

    /**
     * @param username the username to set
     */
    public void setUsername(String username) {
        this.username = username;
    }

}

更新3

这是客户端:

function loadContent(sUsername, sPath)
        {
            arrayContentBeans = new Array();
            var sUrl = "http://localhost:8080/crosscloudservice/services/RDF/retrieveContent?username="+sUsername+"&path="+sPath;
            $.ajax({
                    type: "GET",
                    url: sUrl,
                    contentType: "application/json",
                    dataType: "json",
                    async: false,
                    success: function parse(resp, status, xhr) {
                       $("#message").html("STATUS: " + xhr.status + " " + xhr.statusText + "\n" + resp);
                       $("#message").hide();
                       $.each(resp, function() {
                            $.each(this, function(i, cb) {
                                arrayContentBeans.push(cb);
                            });
                       });

                       renderContent();
                    },
                    error: function(resp, status, xhr){
                        $("#message").html("ERROR: " + resp.status + " " + resp.statusText + "\n" + xhr);
                        $("#message").show();
                    }

                });

        }

更新4

[ {
  "username" : "mzereba",
  "attributes" : {
    "name" : "profile/",
    "size" : 0.2,
    "type" : false,
    "lastModified" : 1410947312123
  },
  "rdf" : {
    "text" : null
  },
  "acl" : {
  }
} ]

1 个答案:

答案 0 :(得分:0)

您可以使用Jackson

ContentBean oContentBean = buildResult(Username, Path);
List<ContentBean> lContentBeans = new ArrayList<ContentBean>();
lContentBeans.add(oContentBean);

ObjectWriter ow = new ObjectMapper()
            .configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false)
            .writer()
            .withDefaultPrettyPrinter();

String result = "";
try {
    result = ow.writeValueAsString(lContentBeans);
} catch(IOException ioe) {
    //do something
}
return result;

这将返回String,因此请相应地更改方法声明。

这里是jar的download link

编辑2: 由于您的List只包含一个元素,因此您可以直接序列化它,以便您不再需要创建List

ContentBean oContentBean = buildResult(Username, Path);

ObjectWriter ow = new ObjectMapper()
            .configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false)
            .writer()
            .withDefaultPrettyPrinter();

String result = "";
try {
    result = ow.writeValueAsString(oContentBean);
} catch(IOException ioe) {
    //do something
}
return result;