Min*_*goo 10 arrays json list utf-8 jackson
现在我正在尝试将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对象时才会出现此问题.如果我写单个数据对象,例如下面的例子中的客户对象,则没有??? 字符和UTF-8正在使用以下代码.
PrintWriter out = response.getWriter();
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(customer);
out.print(json);
Min*_*goo 13
答案很简单.您还需要在response.setContentType中指定UTF-8字符集编码.
response.setContentType("application/json;charset=UTF-8");
然后,上面的许多代码将正常工作.我将保留原样,因为它将向您展示向客户端编写JSON的几种方法.
| 归档时间: | 
 | 
| 查看次数: | 23404 次 | 
| 最近记录: |