代码之家  ›  专栏  ›  技术社区  ›  Dan

如何从restwebservicespring返回自定义响应

  •  0
  • Dan  · 技术社区  · 6 年前

    我期待着结果 确切地 如下(你可以看到单引号)

    {
        "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);  
        }
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   pirho    6 年前

    亚历山德罗·鲍尔 answer 是绝对正确的你可能别无选择。

    很明显,所需的响应不是有效的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;
    
        2
  •  4
  •   Alessandro Power    6 年前

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

    但是JSON标准不允许使用单引号字符串。如果你 真正地