我的问题可能已经在StackoverFlow上得到了回答,但是我找不到。我的问题很简单:我通过API请求数据,并且返回的数据具有Unicode字符,例如:
"SpecialOffer":[{"title":"Offre Vente Priv\u00e9e 1 jour 2019 2020"}]
我需要将“ \ u00e9e”转换为“é”。我无法创建“ replaceAll”,因为我无法事先知道所有字符。
我尝试这个:
byte[] utf8 = reponse.getBytes("UTF-8")
String string = new String(utf8, "UTF-8");
但是该字符串仍然具有“ \ u00e9e”
也是这个:
byte[] utf8 = reponse.getBytes(StandardCharsets.UTF_8);
String string = new String(utf8, StandardCharsets.UTF_8);
也尝试过这个:
string = string.replace("\\\\", "\\");
byte[] utf8Bytes = null;
String convertedString = null;
utf8Bytes = string.getBytes("UTF8") -- Or StandardCharsets.UTF_8 OR UTF-8 OR UTF_8;
convertedString = new String(utf8Bytes, "UTF8") -- Or StandardCharsets.UTF_8 OR UTF-8 OR UTF_8;;
System.out.println(convertedString);
return convertedString;
但是它也不起作用。
我测试了其他方法,但我认为我删除了所有类似的方法,但均无法正常工作,因此无法在此处向您展示。
我确信有一个非常简单的方法,但是我不应该在互联网上搜索正确的词汇。你能帮我吗?
祝您有个美好的一天,并在此先感谢您。
您的输入看起来像是JSON摘录。如果API返回了一个JSON字符串,则只需使用JSON模块对其进行解析:
t = '{"SpecialOffer":[{"title":"Offre Vente Priv\u00e9e 1 jour 2019 2020"}]}'
print(json.loads(t))
给予:
{'SpecialOffer': [{'title': 'Offre Vente Privée 1 jour 2019 2020'}]}
注意:我必须添加大括号以使字符串成为有效的JSON ...
String.getBytes方法需要有效的字符集[1]
来自javadoc [2]的有效情况是>>
因此您需要在getBytes方法中使用UTF-8。
[1]https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#getBytes-java.nio.charset.Charset-[2] https://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html
您可以使用小型json库