Returning an ArrayList from a WebService in Java

2019-04-20 21:02发布

I am having a problem returning an ArrayList from my web service (Java).

I have written a test web service and client which consumes it. All appears to work fine - that is the client is calling the server and the server receives the operation request.

However, I have written a simple method that I want it to return an ArrayList.

I have my interface definition as follows:

@WebService
@SOAPBinding(style = Style.RPC)
public interface ISQLServerConnectionWS {

    @WebMethod
    ArrayList getSimpleArrayList();
}

I have my server side implementation to return the ArrayList:

@WebService(endpointInterface="WebServices.ISQLServerConnectionWS")
public class SQLConnectionWSServer
    implements ISQLServerConnectionWS {

    @Override
    public ArrayList getSimpleArrayList() {
        ArrayList al = new ArrayList();
        al.add( "This" );
        al.add( "is" );
        al.add( "a" );
        al.add( "test" );
        return al;
    }
}

And finally my client call to it:

ArrayList results = server.getSimpleArrayList();

The server populates the array list fine. However, back at the client side, the ArrayList is empty. It has a size of 0.

If I examine the WSDL at my URL (http://127.0.0.1:9876/myservice-sql?wsdl) for the executeSelectSQL, it looks like:

<message name="executeSelectSQLResponse">
    <part name="return" type="tns:arrayList"/>
</message>

Am I missing something obvious?

Edit:

However, if I have a web method defines in the interface as:

@WebMethod
String getAString();

and the server implementation:

@Override
public String getAString() {
    return "hello there";
}

then this works fine - "hello there" is received on the client.

2条回答
疯言疯语
2楼-- · 2019-04-20 21:15

I will suggest create separate pojo class where declare a vaiable

private ArrayList ListData;

create setter/getter method and use the POJO class in your main class to set the arraylist. At same time the Operation getSimpleArrayList change the return type to that of POJO type. Accordingly change the wsdl file too.

查看更多
一夜七次
3楼-- · 2019-04-20 21:35

Use an array instead of an ArrayList as JAXB cannot handle collections as top-level objects, only as properties of beans. Alternatively, create a bean and put the ArrayList in it.

See bug: JAXB-223: JAXB doesn't support collection classes as top level objects

查看更多
登录 后发表回答