簡體   English   中英

如何從其余Webservice Spring返回自定義響應

[英]how to return custom response from rest webservice spring

我期待輸出酷似下面(你看到的單引號)

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

但目前我越來越像這樣:(我們必須從中刪除雙引號)

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

休息法

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

對於那些暗示他只是將實際列表放在地圖中的人:這個問題要求列表的輸出具有單引號的字符串。

但是,JSON標准不允許使用單引號引起來的字符串。 如果您確實想執行此操作,則可能必須破解一種避免JSON序列化的解決方案,並將整個偽JSON響應手動寫入響應主體。 當然,這是一個可怕的主意。 相反,您應該重新考慮使用單引號引起來的字符串的要求。

雖然亞歷山德羅·鮑爾(Alessandro Power)的答案是絕對正確的,但您可能別無選擇。

顯然,所需的響應不是有效的JSON,但訣竅是返回字符串。 因此,構造並返回一個字符串,而不是ResponseEntity 聲明您的方法,例如:

public String getFriendListByEmail(...)

在其主體中,不要使用Map而是這樣的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM