Dan
Dan

Reputation: 2174

how to return custom response from rest webservice spring

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

{
    "success": true,
    "friends":  ['[email protected]','[email protected]','[email protected]','[email protected]','[email protected]'] ,
    "count": 5
}

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

{
    "success": true,
    "friends": "['[email protected]','[email protected]','[email protected]','[email protected]','[email protected]']",
    "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);  
    }

Upvotes: 0

Views: 1144

Answers (2)

pirho
pirho

Reputation: 12205

While Alessandro Power's answer is absolutely correct you might have no option.

It is clear that the required response is not valid JSON but the trick is to return a string. So construct and return a string instead of ResponseEntity. Declare your method like:

public String getFriendListByEmail(...)

In its body do not use Map but something like this:

String s = "{\"success\": true, ";
ObjectMapper om = new ObjectMapper();
s += "\"friends\": " + om.writeValueAsString(myList).replace('"', '\'') + ", ";
s += "\"count\": " + myList.size();
s += "}";
return s;

Upvotes: 2

Alessandro Power
Alessandro Power

Reputation: 2472

To those suggesting he just place the actual list in the map: the question requires that the output of the list have single quoted strings.

But single quoted strings are not allowed by the JSON standard. If you really want to do this you'd probably have to hack a solution that avoids the JSON serialization and manually writes your entire pseudo-JSON response to the response body. This, of course, is a terrible idea; instead you should revisit your requirement to have single quoted strings.

Upvotes: 4

Related Questions