ObjectMapper没有正确处理UTF-8? [英] ObjectMapper Not Handling UTF-8 Properly?

查看:2217
本文介绍了ObjectMapper没有正确处理UTF-8?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ObjectMapper将我系统中的帖子序列化为json。这些帖子包含来自世界各地的条目,并包含utf-8字符。问题是ObjectMapper似乎没有正确处理这些字符。例如,字符串Muséed'Orsay被序列化为Mus?©e d'Orsay。

I'm using ObjectMapper to serialize posts in my system to json. These posts contain entries from all over the world and contain utf-8 characters. The problem is that the ObjectMapper doesn't seem to be handling these characters properly. For example, the string "Musée d'Orsay" gets serialized as "Mus?©e d'Orsay".

这是我的代码正在进行序列化:

Here's my code that's doing the serialization:

public static String toJson(List<Post> posts) {
        ObjectMapper objectMapper = new ObjectMapper()
            .configure(Feature.USE_ANNOTATIONS, true);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            objectMapper.writeValue(out, posts);
        } catch (JsonGenerationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return new String(out.toByteArray());
    }

有趣的是,完全相同的列表< Post>当我使用@ResponseBody使用以下配置通过请求处理程序返回时,获取序列化很好:

Interestingly, the exact same List<Post> posts gets serialized just fine when I return it via a request handler using @ResponseBody using the following configuration:

public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    ObjectMapper m = new ObjectMapper()
        .enable(Feature.USE_ANNOTATIONS)
        .disable(Feature.FAIL_ON_UNKNOWN_PROPERTIES);
    MappingJacksonHttpMessageConverter c = new MappingJacksonHttpMessageConverter();
    c.setObjectMapper(m);
    converters.add(c);
    super.configureMessageConverters(converters);
}

非常感谢任何帮助!

推荐答案

除了转换之外,如何将流程简化为:

Aside from conversions, how about simplifying the process to:

return objectMapper.writeValueAsString(posts);

加速了这个过程(无需从POJO到字节到数组解码到char到build String)以及(更重要的是)缩短代码。

which speeds up the process (no need to go from POJO to byte to array to decode to char to build String) as well as (more importantly) shortens code.

这篇关于ObjectMapper没有正确处理UTF-8?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆