[英]Escape Latin-1 ( ISO-8859-1) to utf-8 String in Java
I tried to use Gson and org.json as the examples. 我尝试使用Gson和org.json作为示例。 I tried Commons Text as well, but I doesn't work for me, when I import the library manually (I not allowed to use Maven). 我也尝试了Commons Text ,但是当我手动导入库时,我不能为我工作(我不允许使用Maven)。 So I decided to search for another solution. 所以我决定寻找另一种解决方案。
NoClassDefFoundError: org/apache/commons/text/StringEscapeUtils NoClassDefFoundError:org / apache / commons / text / StringEscapeUtils
I need to escape an Array to Json this way. 我需要以这种方式将数组转义为Json。 Especially Ó
, ó
or any Latin-1 character( Not escape "
, just escape what is in "&%$/"Helló"
). 特别是Ó
, ó
或任何拉丁语1字符(不逃避"
,只是逃避"&%$/"Helló"
)。 Original message: Helló / // \\ "WÓRLD"
原Helló / // \\ "WÓRLD"
: Helló / // \\ "WÓRLD"
{"token":"045-245","message":"Helló / // \\ \"WÓRLD\" "}
to 至
{"token":"045-245","message":"Hell\u00F3 / // \\ \"W\u00D3RLD\" "}
This what I get when I use: 这是我用的时候得到的:
Gson GSON
JsonObject json = new JsonObject();
json.addProperty("token", "045-245");
json.addProperty("message", "Helló WÓRLD");
String payload = new Gson().toJson(json);
System.out.println(payload);
Result: 结果:
{"token":"045-245","message":"Helló WÓRLD"}
org.json org.json
JSONObject jsonObject = new JSONObject();
jsonObject.put("token", "045-245");
jsonObject.put("message", "Helló WÓRLD");
System.out.println(jsonObject.toString());
Result: 结果:
{"message":"Helló WÓRLD","token":"045-245"}
Thanks to @dnault I found Jackson Json Library. 感谢@dnault我找到了杰克逊杰森图书馆。 I needed to import com.fasterxml.jackson.core
, com.fasterxml.jackson.databind
. 我需要导入com.fasterxml.jackson.core
, com.fasterxml.jackson.databind
。 I imported com.fasterxml.jackson.annotations
as well, for no problems on JDK 8. 我也导入了com.fasterxml.jackson.annotations
,因为JDK 8没有问题。
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class Foo {
ObjectMapper mapper = new ObjectMapper();
mapper.getFactory().configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
ObjectNode node = mapper.getNodeFactory().objectNode();
node.put("token", "045-245");
node.put("message", "Helló / // \\ \"WÓRLD\" ");
System.out.println(mapper.writeValueAsString(node));
}
Output: 输出:
{"token":"045-245","message":"Hell\u00F3 / // \\ \"W\u00D3RLD\" "}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.