现在我正在尝试将 Java List 对象转换为 JSON 数组,并努力转换 UTF-8 字符串。我已经尝试了以下所有方法,但都不起作用。
设置。
response.setContentType("application/json");
PrintWriter out = response.getWriter();
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
final ObjectMapper mapper = new ObjectMapper();
测试#1。
// Using writeValueAsString
String json = ow.writeValueAsString(list2);
测试#2。
// Using Bytes
final byte[] data = mapper.writeValueAsBytes(list2);
String json = new String(data, "UTF-8");
测试#3。
// Using ByteArrayOutputStream with new String()
final OutputStream os = new ByteArrayOutputStream();
mapper.writeValue(os, list2);
final byte[] data = ((ByteArrayOutputStream) os).toByteArray();
String json = new String(data, "UTF-8");
测试#4。
// Using ByteArrayOutputStream
final OutputStream os = new ByteArrayOutputStream();
mapper.writeValue(os, list2);
String json = ((ByteArrayOutputStream) os).toString("UTF-8");
测试#5。
// Using writeValueAsString
String json = mapper.writeValueAsString(list2);
测试#6。
// Using writeValue
mapper.writeValue(out, list2);
就像我说的,以上都不起作用。全部显示“???”等字符。我很感激你的帮助。我正在使用 Servlet 向客户端发送 JSON 响应。
这个问题仅在我编写 java.util.List 对象时发生。如果我写单个数据对象,例如下面的例子中的 customer 对象,那么就没有 ???字符,UTF-8 正在使用以下代码。
PrintWriter out = response.getWriter();
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(customer);
out.print(json);
答案很简单。您还需要在response.setContentType中指定UTF-8字符集编码。
response.setContentType("application/json;charset=UTF-8");
然后,上面的许多代码就可以正常工作了。我将保留我的问题,因为它将向您展示向客户端编写 JSON 的几种方法。
控制器中的请求映射:
@RequestMapping(value = "/user/get/sth",
method = RequestMethod.GET,
produces = { "application/json;**charset=UTF-8**" })
无论其价值如何,如果您要将内容写入文件,那么您需要在 Java 17 中创建 FileWriter 时指定编码:
try (FileWriter jsonFileWriter = new FileWriter(tmpFile, StandardCharsets.UTF_8)) {
objectMapper.writeValue(jsonFileWriter, report);
}
如果您想将 Java 对象转换为 UTF-8 编码的 JSON 字符串,理想情况下不必担心,因为 Java 的 String 本身就是 UTF-16。您无需担心编码,直到您需要将此字符串写入字节流,或写入文件(见上文)或通过网络。
但是如果你需要从字符串中获取UTF-8编码的byte[],你可以使用
String.getBytes(StandardCharsets.UTF_8)
。喜欢
public byte[] toJsonStringUTF8(Object yourObject) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(yourObject);
return jsonString.getBytes(StandardCharsets.UTF_8);
}