Read Json Value from cookie in java. | Community
Skip to main content
Level 2
December 17, 2023

Read Json Value from cookie in java.

  • December 17, 2023
  • 3 replies
  • 1505 views

Hi, I want to get and decode a cookie in java, which is set in JavaScript. while trying to get the cookie this error occurred Json Exception::A JSONObject text must begin with '{' at 1 [character 2 line 1].

This is decoded JSON which is encoded in JavaScript.

 {
   "name": "prodname",
   "quantity": 4
}

To decode the cookie, we have used base64 decoder.

final Cookie cookie = getCookie(request, "XYZ");

JsonObject cookieJson = new JsonParser().parse(new String(Base64.getDecoder().decode(cookie.getValue()))).getAsJsonObject();

Kindly anyone help to fix this. Thanks in advance!

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.

3 replies

aanchal-sikka
Community Advisor
Community Advisor
December 18, 2023

@harinivr Sometimes, extra whitespaces at the beginning of the cookie value can cause parsing issues. You might want to trim the cookie value before decoding and parsing it.

String trimmedCookieValue = cookie.getValue().trim(); JsonObject cookieJson = new JsonParser().parse(new String(Base64.getDecoder().decode(trimmedCookieValue))).getAsJsonObject();

 

Aanchal Sikka
Kamal_Kishor
Community Advisor
Community Advisor
December 18, 2023

Hi @harinivr : Can you please check the value of cookie.getValue(), either by putting a logger or in debug mode. That should help you find the reason for this error.

Kamal_Kishor
Community Advisor
Community Advisor
December 26, 2023

@harinivr - were you you able to find the issue? Let me know if you still need some pointers on this. Thanks.

kautuk_sahni
Community Manager
Community Manager
January 11, 2024

@harinivr Did you find the suggestions from users helpful? Please let us know if more information is required. Otherwise, please mark the answer as correct for posterity. If you have found out solution yourself, please share it with the community.

Kautuk Sahni