Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - decode unicode characters without StringEscapeUtils?

When I use Gson (JsonParser.parse) to decode the following:

{ "item": "Bread", "cost": {"currency": "\u0024", "amount": "3"}, "description": "This is bread\u2122. \u00A92015" }

The "currency" element is returned as a string of characters (and is not converted to a unicode character). Is there a setting or method in Gson that could help me?

If not, is there any way in Android to convert a string that contains one or more escaped character sequences (like "\u0024") to an output string with unicode characters (without writing my own and without using StringEscapeUtils from Apache)?

I'd like to avoid adding another library (for just one small feature).

Update

Looks like the server was double escaping the back slash in the unicode escape sequence. Thanks everyone for your help!

like image 404
Mitkins Avatar asked Feb 11 '15 04:02

Mitkins


2 Answers

Is it only me or is it really more complicated than simply using TextView's setText() method? Anyhow, following is working just fine on my end with the given sample json (put the sample to assets and read it using loadJSONFromAsset()):

JsonParser parser = new JsonParser();
JsonElement element = parser.parse(loadJSONFromAsset());
JsonObject obj = element.getAsJsonObject();
JsonObject cost = obj.getAsJsonObject("cost");
JsonPrimitive sign = cost.get("currency").getAsJsonPrimitive();

TextView tv = (TextView)findViewById(R.id.dollar_sign);
tv.setText(sign.getAsString());
like image 54
ozbek Avatar answered Sep 27 '22 16:09

ozbek


Gson returns "$". Something is wrong in your set up.

String s = "{ \"item\": \"Bread\", \"cost\": {\"currency\": " 
    + "\"\\u0024\", \"amount\": \"3\"}, \"description\": " 
    + "\"This is bread\\u2122. \\u00A92015\" }\n";
JsonElement v = new JsonParser().parse(s);
assertEquals("$", v.getAsJsonObject().get("cost").getAsJsonObject()
    .get("currency").getAsString());
like image 23
Jesse Wilson Avatar answered Sep 27 '22 18:09

Jesse Wilson