json - 在 Java 中使用 UTF-8 编码 Json 对象数据
问题描述
假设我的 JSON 数据中有任何特殊字符,它们都需要用 UTF-8 编码。
示例 JSON:
String msg = { \"name\": \"SÅi®äjesh\", \"location\":\"Öslö" };
我在下面尝试过
byte[] utf8Bytes = msg.getBytes(StandardCharsets.UTF_8);
String newString = new String(utf8Bytes, StandardCharsets.UTF_8);
/* 显示?在我的控制台中标记符号 */
System.out.println(URLEncoder.encode( original,StandardCharsets.UTF_8.toString() ));
/* 对包含 {、" 等符号的总字符串进行编码。*/
解决方案
Java 字符串是 UTF-16,您需要将其转换为字节数组,然后再转换为 utf8 字符串。
import static java.nio.charset.StandardCharsets.*;
byte[] bytes = "YOUR JSON".getBytes(ISO_8859_1);
String jsonStr = new String(bytes, UTF_8);
推荐阅读
- google-cloud-platform - 如何在 BigQuery 上启用成本控制?
- javascript - 如何使用 jestJS 模拟嵌套函数
- c++ - 什么时候为派生类初始化 vptr?
- javascript - 调用ajax后如何在新的HTML页面中显示结果
- regex - 匹配字符串中的不同模式
- python - Python 集花费的内存量逐步增加
- javascript - 在javascript数组中检查并转换具有条件的重复对象
- c# - 以泛型表达式和动作作为参数调用方法
- node.js - 如何在电子应用程序 windows/mac 中检查设备连接到哪个网络和 VPN?
- android - 将片段添加到 BackStack 不断抛出错误