Expand my Community achievements bar.

Don’t miss the AEM Skill Exchange in SF on Nov 14—hear from industry leaders, learn best practices, and enhance your AEM strategy with practical tips.

Read Json Value from cookie in java.

Avatar

Level 2

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!

4 Replies

Avatar

Community Advisor

@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

Avatar

Community Advisor

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.

Avatar

Community Advisor

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

Avatar

Administrator

@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