Java List to JSON array using Jackson with UTF-8 encoding
arrays, jackson, json, list, utf-8
Solution
The answer was very simple. You need to specify UTF-8 charset encoding in response.setContentType too.
response.setContentType("application/json;charset=UTF-8");
Then, many of above code will work correctly. I will leave my question as is, since it will show you several ways of writing JSON to clients.
Problem
Now I'm trying to convert Java List object to JSON array, and struggling to convert UTF-8 strings. I've tried all followings, but none of them works. Settings. ``` response.setContentType("application/json"); PrintWriter out = response.getWriter(); ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); final ObjectMapper mapper = new ObjectMapper(); ``` Test#1. ``` // Using writeValueAsString String json = ow.writeValueAsString(list2); ``` Test#2. ``` // Using Bytes final byte[] data = mapper.writeValueAsBytes(list2); String json = new String(data, "UTF-8"); ``` Test#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"); ``` Test#4. ``` // Using ByteArrayOutputStream final OutputStream os = new ByteArrayOutputStream(); mapper.writeValue(os, list2); String json = ((ByteArrayOutputStream) os).toString("UTF-8"); ``` Test#5. ``` // Using writeValueAsString String json = mapper.writeValueAsString(list2); ``` Test#6. ``` // Using writeValue mapper.writeValue(out, list2); ``` Like I said, none of above works. All displays characters like "???". I appreciate your helps. I'm using Servlet to send JSON response to clients. This problem only happens when I write java.util.List object. If I write single data object, e.g. customer object in below example, then there is no ??? characters, and UTF-8 is working with the following code. ``` PrintWriter out = response.getWriter(); ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); String json = ow.writeValueAsString(customer); out.print(json); ```