我需要 jackson-dataformat-xml
方面的帮助。我需要序列化List<String>
使用XmlMapper
将引号 "
编码到 xml 中→ "
.
但是序列化后XmlMapper
对所有其他特殊符号( <
、 >
、 &
等)进行编码,但完全忽略引号( '
和 "
)...如果我在序列化之前手动对字符串进行编码,则内容会变得困惑,因为"
有'&'
里面的序列化为 &quot;
而不是当然。
也许有人知道如何让它发挥作用?
另外,有没有办法解决 List<String>
上禁用自动特殊符号编码的问题字段使用 @JacksonRawValue
或类似的东西?此注释在简单(非数组)字段上效果很好,但在 List<String>
上无法正常工作。 .
谢谢。
最佳答案
问题是这样解决的。我使用了 woodbox Stax2 扩展。 这很有帮助。 https://github.com/FasterXML/jackson-dataformat-xml/issues/75
XmlMapper xmlMapper = new XmlMapper(module);
xmlMapper.getFactory().getXMLOutputFactory().setProperty(XMLOutputFactory2.P_TEXT_ESCAPER,
new CustomXmlEscapingWriterFactory());
这里是工厂。
public class CustomXmlEscapingWriterFactory implements EscapingWriterFactory {
public Writer createEscapingWriterFor(final Writer out, String enc) {
return new Writer(){
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
String val = "";
for (int i = off; i < len; i++) {
val += cbuf[i];
}
String escapedStr = StringEscapeUtils.escapeXml(val);
out.write(escapedStr);
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void close() throws IOException {
out.close();
}
};
}
public Writer createEscapingWriterFor(OutputStream out, String enc) {
throw new IllegalArgumentException("not supported");
}
}
关于java - 使用 jackson-dataformat-xml 转义引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56799368/