使用Jackson和UTF-8编码的Java列表到JSON数组

lmvvr0a8  于 6个月前  发布在  Java
关注(0)|答案(3)|浏览(69)

现在我正在尝试将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);

2nc8po8w

2nc8po8w1#

答案很简单,你需要在response.setContentType中指定UTF-8字符集编码。

response.setContentType("application/json;charset=UTF-8");

字符串
然后,上面的许多代码将正确工作。我将离开我的问题,因为它将向您展示几种向客户端编写JSON的方法。

a8jjtwal

a8jjtwal2#

在Controller中的RequestMapping上:

@RequestMapping(value = "/user/get/sth",
                method = RequestMethod.GET,
                produces = { "application/json;**charset=UTF-8**" })

字符串

vwoqyblh

vwoqyblh3#

为了它的价值,如果你要将内容写入文件,那么你需要在Java 17中创建FileWriter时指定编码:

try (FileWriter jsonFileWriter = new FileWriter(tmpFile, StandardCharsets.UTF_8)) {
    objectMapper.writeValue(jsonFileWriter, report);
}

字符串
如果你想把Java对象转换成一个UTF-8编码的JSON字符串,理想情况下这不应该是一个问题,因为Java的字符串本身就是UTF-16。你不需要担心编码,直到你需要把这个字符串写到一个字节流,或者输出到一个文件(见上文),或者通过网络。
但是如果你需要从String中获取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);
}

相关问题