Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jsonObject.addProperty Method is adding unnecessary Quotation Marks and Slashes to it's value

This is my String

String currentTokenNo = "/SUeSjUf0A0aLFr+wVIZbw==\nLmmWtgHZ90yH0NBoATYB/A"

I've Added This String to my JsonObject which is a class of com.google.gson.JsonObject package

  JsonObject jsonToSubmit = new JsonObject();

    try {

        jsonToSubmit.addProperty("token", currentTokenNo);

      } catch (Exception e) {

        e.printStackTrace();
     }

But when I Log my String and JsonObject

Log.d("mainactivityjson", "Current Token No : "+currentTokenNo );
Log.d("mainactivityjson", "jsonToSubmit : "+jsonToSubmit);

I found the result

D/mainactivityjson: Current Token No : "/SUeSjUf0A0aLFr+wVIZbw==\nLmmWtgHZ90yH0NBoATYB/A"
D/mainactivityjson: jsonToSubmit : {"token":"\"/SUeSjUf0A0aLFr+wVIZbw==\\nLmmWtgHZ90yH0NBoATYB/A\""}

Now, My question is :

Why those quotation marks and slashes are added to value of JsonObject? Is there any suitable reason of it ?

It is really hampering the process of checking String's value at server side.

I've Done a temporary solution to accomplish the task by trimming single character from both side like following

jsonToSubmit.addProperty("token",currentTokenNo.substring(1,currentTokenNo.length()-1));

This worked Perfectly But I don't think It's a better idea for future !!!

Additional Information :

Variable currentTokenNo is not declared directly as shown above, It was retrieved from SharedPreferences & If it is declared directly then everything works fine.

String currentTokenNo = preferences.getString(LOGINCRED_TOKEN,"");

If the same variable is declared directly, Everything works fine.

Any kind of help will be appreciated.

like image 622
Shree Krishna Avatar asked Jan 03 '16 11:01

Shree Krishna


1 Answers

From your comments and logcat info, the actual value getting from SharedPreferences is "/SUeSjUf0A0aLFr+wVIZbw==y9iWl1SSrUe9zRQppENMNA" (having quotation marks), not /SUeSjUf0A0aLFr+wVIZbw==y9iWl1SSrUe9zRQppENMNA. That's why you got jsonToSubmit : {"token":"\"/SUeSjUf0A0aLFr+wVIZbw==y9iWl1SSrUe9zRQppENMNA\""}


UPDATE:

For your temporary solution: jsonToSubmit.addProperty("token",currentTokenNo.substring(1,currentTokenNo.length()-1));

I prefer the following way:

jsonToSubmit.addProperty("token", currentTokenNo.replaceAll("\"",""));

If you also want to remove slashes, then use:

jsonToSubmit.addProperty("token", currentTokenNo.replaceAll("\"","").replaceAll("/",""));

Hope it helps!

like image 50
BNK Avatar answered Sep 23 '22 19:09

BNK