Jackson adds backslash in json

后端 未结 8 890
伪装坚强ぢ
伪装坚强ぢ 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:33

    All strings in java have to escape quotes in them. So jsonInString should have slashes in it. When you output jsonInString though it shouldn't have the quotes. Are you looking at it in a debugger or something?

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题