0

I would like to store a JSON Object in Cookie. Since version 0 cookie values are restrictive in allowed characters, it only allows url safe characters. That's why I encoded it in UTF-8. After encoding it, JSON characters are changed.

Cookie cookie = new Cookie("res", URLEncoder.encode(res, "UTF-8"));
    cookie.setComment("comment");
    cookie.setMaxAge(24*60*60);
    cookie.setPath("/t/res");
    response.addCookie(cookie);

JSON:

{
"evt": [{
    "id": "2",
    "qty": "2"
}, {
    "id": "3",
    "qty": "7"
}],
"exc": [{
    "id": "2",
    "qty": "3"
}, {
    "id": "1",
    "qty": "6"
}],
"qt": "15",
"ti": "067e61623b6f4ae2a1712470b63dff00",
"rm": {
    "aci": "6",
    "rt": "5"
    }
}

This is how it is shown in cookie:

%7B%22evt%22%3A%5B%5D%2C%22exc%22%3A%5B%5D%2C%22qt%22%3A%221%22%2C%22ti%22%3A%22067e61623b6f4ae2a1712470b63dff00%22%2C%22rm%22%3A%7B%22aci%22%3A%226%22%2C%22rt%22%3A%225%22%7D%7D

I parse it in JS JSON.parse(jsn), I get an error Unexpected token o in JSON at position 1

Am I missing something or how exactly can I parse it?

Malena T
  • 341
  • 2
  • 7
  • 22

2 Answers2

0

perhaps use JSON.stringify(res) to make your object, this always seems pretty safe to me when encoding/decoding something I want to store, rather than using your URLEncoder here.

0

After encoding uri, you also eed to decode it before parsing.
var x= java.net.URLDecoder.decode(jsn, "UTF-8");
Use JSON.parse(x) instead of JSON.parse alone If this isn't answer look at this
Decode UTF-8 with Javascript

Shubham
  • 1,288
  • 2
  • 11
  • 32