简体   繁体   English

Spring Web Service:向响应添加数组/集合

[英]Spring Web Service: Adding Arrays/Collections to a response

Currently my webservice will return a response which queries for one specific record. 当前,我的Web服务将返回一个查询,查询一条特定的记录。 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 我返回特定人的姓名,地址1,地址2和邮政编码

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. 他们希望返回传入的邮政编码的所有名称/地址。话虽如此,我的resultExtractor和response当前正在做单个字符串/整数。 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 . 使用spring,您可以使用@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. 然后将解析您的java返回类型并通过电线发送它,如果杰克逊在您的类路径中,则它将转换为JSON。

Spring MVC ResponseBody docs Spring MVC ResponseBody文档

Similar question which has Java and xml config answers 具有Java和xml配置答案的类似问题

The best way is to use Json in the response. 最好的方法是在响应中使用Json。 So who make the request will need to convert the json into the right Object. 因此,发出请求的人将需要将json转换为正确的Object。

For example you can use Gson library of google: Gson Library 例如,您可以使用Google的Gson库Gson库

Ther is an example MVC controller that works in my project 这是在我的项目中工作的示例MVC控制器

@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;
            }


} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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