当我使用Gson(JsonParser.parse)解码以下内容时:
{ "item": "Bread", "cost": {"currency": "u0024", "amount": "3"}, "description": "This is breadu2122. u00A92015" }
"currency"元素以字符串形式返回(不会转换为unicode字符)。Gson有什么设置或方法可以帮助我吗?
如果没有,在Android中有没有任何方法可以将包含一个或多个转义字符序列的字符串(如"\u0024")转换为具有unicode字符的输出字符串(无需编写自己的字符串,也无需使用Apache的StringEscapeUtils)?
我希望避免添加另一个库(仅针对一个小功能)。
更新
看起来服务器对unicode转义序列中的反斜杠进行了双重转义。感谢大家的帮助!
是只有我一个人,还是真的比简单地使用TextView
的setText()
方法更复杂?无论如何,对于给定的示例json(将示例放入资产并使用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());
"$"
。你的设置有问题。
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());
您可以将其解析为十六进制
char c = (char)Integer.parseInt(str.substring(2), 16);