【问题标题】:Escape Latin-1 ( ISO-8859-1) to utf-8 String in Java在 Java 中将 Latin-1 (ISO-8859-1) 转义为 utf-8 字符串
【发布时间】:2019-06-03 20:18:41
【问题描述】:

我尝试使用Gsonorg.json 作为示例。我也尝试了Commons Text,但是当我手动导入库时(我不允许使用 Maven),我不适合我。所以我决定寻找另一种解决方案。

NoClassDefFoundError: org/apache/commons/text/StringEscapeUtils

我需要以这种方式将 Array 转义为 Json。尤其是 Óó 或任何 Latin-1 字符(不要转义 ",只是转义 "&%$/"Helló" 中的内容)。原文:Helló / // \ "WÓRLD"

{"token":"045-245","message":"Helló / // \\ \"WÓRLD\" "}

{"token":"045-245","message":"Hell\u00F3 / // \\ \"W\u00D3RLD\" "}

这是我使用时得到的:

格森

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);

结果:

{"token":"045-245","message":"Helló WÓRLD"}

org.json

JSONObject jsonObject = new JSONObject();        
jsonObject.put("token", "045-245");
jsonObject.put("message", "Helló WÓRLD");
System.out.println(jsonObject.toString());

结果:

{"message":"Helló WÓRLD","token":"045-245"}

【问题讨论】:

标签: java json escaping iso-8859-1


【解决方案1】:

感谢@dnault,我找到了 Jackson Json 库。我需要导入com.fasterxml.jackson.corecom.fasterxml.jackson.databind。我也导入了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));

}

输出:

{"token":"045-245","message":"Hell\u00F3 / // \\ \"W\u00D3RLD\" "}

【讨论】:

    猜你喜欢
    • 2020-01-25
    • 2015-03-26
    • 1970-01-01
    • 2014-07-04
    • 2014-08-29
    • 2012-10-08
    • 2010-11-19
    • 2016-07-29
    相关资源
    最近更新 更多