首页 > 解决方案 > 在 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() ));

/* 对包含 {、" 等符号的总字符串进行编码。*/

标签: jsonutf-8encode

解决方案


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

推荐阅读