当数组仅包含一个元素时,JSON响应中的对象数组将作为单个对象接收

时间:2021-10-23 03:34:51

I am sending back in the response an array of objects from my resource, and when the array contains only one element I cannot loop the array because the response turns out to be a single object instead of array containing one object.

我在响应中向我的资源发回一个对象数组,当数组只包含一个元素时,我无法循环数组,因为响应结果是单个对象而不是包含一个对象的数组。

having this code from the front end side:

从前端获得此代码:

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();
        }
    });
}

Anyone can tell me how to force JSON to have an array even when it contains one single object?

任何人都可以告诉我如何强制JSON有一个数组,即使它包含一个单一的对象?

UPDATE 1

Here is the Resource:

这是资源:

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

UPDATE 2

I've added what should serialize my array now jackson-core-2.2.3.jar and the following tag in my web.xml:

我已经添加了应该在我的web.xml中序列化我的数组jackson-core-2.2.3.jar以及以下标记的内容:

<init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>org.qcri.crosscloud.ws;org.codehaus.jackson.jaxrs</param-value>
</init-param>

But no luck, it still behaves the same :( any ideas?

但没有运气,它仍然表现得一样:(任何想法?

1 个解决方案

#1


0  

if you are sending an Array of object then make sure that when there is only one element to send serialize it as Array so the client side will always get same data structure

如果您要发送一个对象数组,那么请确保当只有一个元素要发送时将其序列化为数组,这样客户端将始终获得相同的数据结构

#1


0  

if you are sending an Array of object then make sure that when there is only one element to send serialize it as Array so the client side will always get same data structure

如果您要发送一个对象数组,那么请确保当只有一个元素要发送时将其序列化为数组,这样客户端将始终获得相同的数据结构