首页 > 解决方案 > how to return custom response from rest webservice spring

问题描述

I am expecting output exactly like below(you see single quotes)

{
    "success": true,
    "friends":  ['Kanchhi@example.com','modi@example.com','maya@example.com','jetli@example.com','john@example.com'] ,
    "count": 5
}

but presently i am getting like this:(we have to remove double quotes from this)

{
    "success": true,
    "friends": "['Kanchhi@example.com','modi@example.com','maya@example.com','jetli@example.com','john@example.com']",
    "count": 5
}

Rest method

@PostMapping(path = "/my", consumes = MediaType.TEXT_PLAIN_VALUE)
    public ResponseEntity<Map> getFriendListByEmail(@Valid @RequestBody String value) { 
                LinkedHashMap<Object, Object> map23 = new LinkedHashMap<>(); 
                myList=userService.getfriendList(value); //getting some list say we have got 5 list of emails
                String s  ="'"+myList.toString().replace("[","").replace("]", "").replace(" ","").replace(",","','")+"'"; 
                map23.put("success", true);
                map23.put("friends", "["+s+"]"); // trying to put the updated string 
                map23.put("count", myList.size());  
                return new ResponseEntity<Map>(map23, HttpStatus.OK);  
    }

标签: javaspringrestspring-boot

解决方案


对于那些建议他将实际列表放在地图中的人:问题要求列表的输出具有单引号字符串。

但是 JSON 标准不允许使用单引号字符串。如果你真的想这样做,你可能不得不破解一个避免 JSON 序列化并手动将整个伪 JSON 响应写入响应正文的解决方案。当然,这是一个可怕的想法。相反,您应该重新考虑使用单引号字符串的要求。


推荐阅读