Jackson adds backslash in json

后端 未结 8 1080
伪装坚强ぢ
伪装坚强ぢ 2020-12-31 00:55

I\'m building REST service on Jersey and using Jackson to produce JSON from java classes of my model. Model with absolutely simple values, I think

8条回答
  •  盖世英雄少女心
    2020-12-31 01:35

    I don't know why, but in my case it works doing this :

    private static final String COOKIE_TEMPLATE = "{0}={1};Version={2};Domain={3};Max-Age={4};Path='/'";
    
    response.addHeader("Set-Cookie", MessageFormat.format(COOKIE_TEMPLATE, cookie.getName(),cookie.getValue(), cookie.getVersion(), cookie.getDomain(),Integer.toString(cookie.getMaxAge())));
    return ResponseEntity.ok(...);
    

    cookie is a javax.servlet.http.Cookie, and cookie.getValue() contains a string produced by

    ObjectMapper mapper = new ObjectMapper();
    return mapper.writeValueAsString(obj);
    

    If I use

    response.addCookie(cookie)
    

    I have a resulting cookie definition as JSON with backslashes.

    But, if I use

    response.addHeader("Set-Cookie",MessageFormat(TEMPLATE,cookie.get...))
    

    I managed the same resulting cookie definition as JSON, but without backslashes.

    In case of having several cookies, addHeader("Set-Cookie") only creates/updates the desired cookie. The other ones are maintained and won't be altered.

提交回复
热议问题