简体   繁体   中英

Spring Web Service: Adding Arrays/Collections to a response

Currently my webservice will return a response which queries for one specific record. A request has been made to allow for multiple similar records to be returned via the response message.

For Example:

I return name, address 1, address 2, postalcode for a specific person

They'd like to have a return of all names/addresses for the postalcode passed in. With that being said, my resultExtractor and response are doing single strings/ints currently. Is there any documentation out there explaining the process of using arrays with your response message?

Thanks!

Using spring, you can annotate the controller method with @ResponseBody . Your java return type will be then be parsed and sent over the wire, if jackson is on your classpath then it will be converted to JSON.

Spring MVC ResponseBody docs

Similar question which has Java and xml config answers

The best way is to use Json in the response. So who make the request will need to convert the json into the right Object.

For example you can use Gson library of google: Gson Library

Ther is an example MVC controller that works in my project

@RequestMapping(value = "services/utente/getUtenteByUsername", method = RequestMethod.GET)
    @ResponseBody
    public String getUtenteDaUsername( @RequestParam("username") String username, Model model) {

            utente = utenteBo.findByUsername(username);

            String jsonResult = "";

            if (utente != null) {

                    GsonBuilder builder = new GsonBuilder();
                    Gson gson = builder.create();

                    jsonResult = gson.toJson(utente);

                    return jsonResult;
            } 
            else {
                return null;
            }


} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM