如何使用Jackson XmlMapper控制编码? [英] How to control encoding with Jackson XmlMapper?
问题描述
我找不到将序列化XML的编码从默认的UTF-8
更改为ISO-8859-1
的(很明显的)方法.我阅读了使用指南,这使我认为必须有一种方法将XMLOutputFactory
与XmlFactory
结合使用可实现此目的,但是我看不到一种方法来配置这些工厂中的任何一个以默认使用另一种编码,只有createXMLEventWriter
可以在其中传递编码.
I can't find a(n obvious) way to change the encoding for serialized XML from the default UTF-8
to ISO-8859-1
. I read the Usage Guide, which makes me think that there must be a way using XMLOutputFactory
with XmlFactory
to achieve this, but I can't see a way to configure any of those factories to use another encoding by default, there's only createXMLEventWriter
where I could pass in an encoding.
我知道如何使用ToXmlGenerator.Feature.WRITE_XML_DECLARATION
生成XML声明.所以我需要的是这样的声明:
I know how to generate the XML declaration using ToXmlGenerator.Feature.WRITE_XML_DECLARATION
. So what I need is a declaration like this:
<?xml version='1.0' encoding='ISO-8859-1'?>
当然,内容也应该用ISO-8859-1
编码.
And of course the content should be encoded in ISO-8859-1
, too.
推荐答案
在源代码,您会发现UTF-8
是硬编码的:
In the ToXmlGenerator
source code, you'll find that UTF-8
is hard coded:
if (Feature.WRITE_XML_1_1.enabledIn(_formatFeatures)) {
_xmlWriter.writeStartDocument("UTF-8", "1.1");
} else if (Feature.WRITE_XML_DECLARATION.enabledIn(_formatFeatures)) {
_xmlWriter.writeStartDocument("UTF-8", "1.0");
} else {
return;
}
一旦问题 ://github.com/FasterXML/jackson-dataformat-xml"rel =" nofollow noreferrer> jackson-dataformat-xml
项目.
Once ToXmlGenerator
is final
there might not be an easy way to handle it. I've submitted an issue in the jackson-dataformat-xml
project.
If you stick to JAXB, you can control the value of the encoding
attribute using Marshaller.JAXB_ENCODING
:
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "ISO-8859-1");
marshaller.marshal(foo, System.out);
查看此答案.
这篇关于如何使用Jackson XmlMapper控制编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!