使用UTF-8编码的Jackson ObjectMapper ?

时间:2023-01-06 08:13:42

Is there a way to tell Jackson to use UTF-8 encoding when using ObjectMapper to serialize and deserialize Objects?

在使用ObjectMapper序列化和反序列化对象时,是否有办法告诉Jackson使用UTF-8编码?

1 个解决方案

#1


39  

Jackson automatically detects encoding used in source: as per JSON specification, only valid encodings are UTF-8, UTF-16 and UTF-32. No other encodings (like Latin-1) can be used. Because of this, auto-detection is easy and done by parser -- no encoding detection is accepted for this reason. So, if input is UTF-8, it will be detected as such.

Jackson自动检测源代码中使用的编码:根据JSON规范,只有有效的编码是UTF-8、UTF-16和UTF-32。没有其他编码(如Latin-1)可以使用。因此,自动检测很容易,并且由解析器完成——因此不接受编码检测。因此,如果输入是UTF-8,它就会被检测到。

For output, UTF-8 is the default; but if you explicitly want to use another encoding, you can create JsonGenerator explicitly (with a method that takes JsonEncoding), and pass this to ObjectMapper.

对于输出,默认是UTF-8;但是,如果您明确地希望使用另一种编码,您可以显式地创建JsonGenerator(使用接受JsonEncoding的方法),并将其传递给ObjectMapper。

Alternatively in both cases you can of course manually construct java.io.Reader / java.io.Writer, and make it use whatever encoding you want.

当然,也可以在这两种情况下手动构建java.io。读者/ io。写入,并使它使用任何你想要的编码。

#1


39  

Jackson automatically detects encoding used in source: as per JSON specification, only valid encodings are UTF-8, UTF-16 and UTF-32. No other encodings (like Latin-1) can be used. Because of this, auto-detection is easy and done by parser -- no encoding detection is accepted for this reason. So, if input is UTF-8, it will be detected as such.

Jackson自动检测源代码中使用的编码:根据JSON规范,只有有效的编码是UTF-8、UTF-16和UTF-32。没有其他编码(如Latin-1)可以使用。因此,自动检测很容易,并且由解析器完成——因此不接受编码检测。因此,如果输入是UTF-8,它就会被检测到。

For output, UTF-8 is the default; but if you explicitly want to use another encoding, you can create JsonGenerator explicitly (with a method that takes JsonEncoding), and pass this to ObjectMapper.

对于输出,默认是UTF-8;但是,如果您明确地希望使用另一种编码,您可以显式地创建JsonGenerator(使用接受JsonEncoding的方法),并将其传递给ObjectMapper。

Alternatively in both cases you can of course manually construct java.io.Reader / java.io.Writer, and make it use whatever encoding you want.

当然,也可以在这两种情况下手动构建java.io。读者/ io。写入,并使它使用任何你想要的编码。