6

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!

Mitkins
  • 4,031
  • 3
  • 40
  • 77

3 Answers3

4

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());
Community
  • 1
  • 1
ozbek
  • 20,955
  • 5
  • 61
  • 84
  • As far as I know, when you create the string literal using the compiler, it automatically converts it into a unicode character for you! I use TextView.setText too, but I see the escape code rather than the character. I think that's because the escape sequence comes from a json string, which is decoded by Gson. – Mitkins Feb 11 '15 at 05:06
  • @Camel: you should probably add more context to the OP then; example input json and how you are parsing would help... – ozbek Feb 11 '15 at 08:07
  • I still can not reproduce the problem. Please see the update above. – ozbek Feb 12 '15 at 03:13
2

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());
Jesse Wilson
  • 39,078
  • 8
  • 121
  • 128
0

You can parse it as a hex number

    char c = (char)Integer.parseInt(str.substring(2), 16);
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275