ANicholasson
ANicholasson

Reputation: 477

Getting org.json.JSONEXCEPTION: Unteterminated object at character when decoding token

So I am trying to decode a JWT token in my android app when using the method Base64.decodeBase64() from import org.apache.commons.codec.binary.Base64;
When I print the string I get from the decoded token, I get these characters at the end of the string "������", when it really should be "}}"

The code is given below:

String token = loadFromCache("token");
String[] split_String = token.split("\\.");
String base64EncodedBody = split_String[1];
System.out.println("BASE64 Body: " + base64EncodedBody);
String body = new String(Base64.decodeBase64(base64EncodedBody.getBytes()));
System.out.println("BODY: " + body);
try {
    JSONObject jsonObject = new JSONObject(body).getJSONObject("employee");
} catch (JSONException e) {
    e.printStackTrace();
}

the token is valid, and I do indeed get almost all the values correct. It's just that it ends with the characters ������ instead of }}. Any help appreciated

Upvotes: 0

Views: 106

Answers (2)

ANicholasson
ANicholasson

Reputation: 477

An alternative solution that uses "import com.auth0.android.jwt.JWT;"

return new JWT(loadFromCache("token")).getClaim("employee").asObject(Employee.class);

This returns the claim "employee" as a Employee object so i can just use getters to get the values.
Example: employee.getId() etc..

NOTE: the loadFromCache method just returns the value specified by its key. Here I want the value defined by the key "token".

Upvotes: 0

Sdghasemi
Sdghasemi

Reputation: 5598

Use Android's Base64 class:

String body = new String(Base64.decode(base64EncodedBody.getBytes(Charset.forName("UTF-8")), Base64.NO_WRAP), Charset.forName("UTF-8"));

With your own Base64 flag and encoding.

Upvotes: 1

Related Questions