简体   繁体   中英

Display unicode characters - Android

I have a json for currencies :

[
  {
    "acronym": "EUR",
    "currency": "Euros",
    "favorite": "true",
    "placeholder": "\\u20ac00.00 EUR",
    "symbol": "\\u20ac"
  }
]

I put this in the asset folder and parse like so:

InputStream stream = context.getAssets().open("currencies.json");
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
str = new String(buffer, "UTF-8");

which I then convert to my pojo object with GSON

Type objectType = new TypeToken<ArrayList<Currency>>(){}.getType();
ArrayList<Currency> currencies = gson.fromJson(json, objectType);
return currencies;

which works fine (my pojo properties are named the same as in the json).

HOWEVER

When I try to display the symbol it doesn't display it as it should, for example I get "\€" instead of "€"

txtAmount.setText(currency.getSymbol());

I've tried the following log

Log.d(currency.getSymbol() + "\u20ac");

Which gives me:

\u20ac€

I don't understand why it won't display the characters properly..

Your JSON has escaped the backslash, which means it's the JSON representation of "backslash u 20ac".

All you need to do is not escape the backslash, so that \€ is the JSON-escaped version of the Euro symbol:

"symbol": "\u20ac"

I'd also suggest using Guava to load your string, with a try-with-resources statement:

String json;
try (Reader reader = 
         new InputStreamReader(context.getAssets().open("currencies.json"),
                               Charsets.UTF_8)) {
    json = CharStreams.toString(reader);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM