【问题标题】:how to convert unicode characters to actual characters in java?如何将unicode字符转换为java中的实际字符?
【发布时间】:2018-06-08 06:24:41
【问题描述】:

我有两个字符串: 1.簿记表格\\u0026模板 2. 霍奇金病

我想将 \\u0026 替换为 & 并将 \u0027 替换为 '。一种方法是用相应的符号替换它们的出现,但是有没有通用的方法来处理这个问题?

【问题讨论】:

  • 这些字符串在哪里?他们来自哪里?
  • 它们是来自 http 请求的 json。
  • 然后 JSON 解析器会自动将这些转义序列转换为字符。
  • 为什么其中一个转义序列以双反斜杠开头,而另一个以单反斜杠开头?有什么区别?

标签: java string character-encoding url-encoding


【解决方案1】:

我的推荐是 Apache StringScapeUtils 特别是 unescapeJava 方法。

网站: https://commons.apache.org/proper/commons-lang/

Maven 仓库: https://mvnrepository.com/artifact/org.apache.commons/commons-lang3

该方法将 unicode 转换为可读文本,例如:

String stringWithUnicode; //For example "tendr\\u00e1"
StringScapeUtils.unescapeJava(stringWithUnicode); //This call returns: Tendrá

【讨论】:

  • 在你的例子中,字符串文字中应该有两个\ s,否则你也可以单独使用文字。
  • 您的代码示例应该使用双反斜杠 StringScapeUtils.unescapeJava("\\u00e1"); ,否则字符串文字已经包含单个字符 á,Java 编译器未转义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-21
  • 1970-01-01
  • 2015-06-30
  • 2014-01-07
  • 2020-08-20
  • 2011-10-27
相关资源
最近更新 更多