杰克逊XML映射器强制使用小写XML标签

时间:2019-09-12 18:05:25

标签: java jackson jackson-databind jackson-dataformat-xml

我正在尝试将带有XMLElement注释的POJO转换为XML字符串。我将变量名大写,注释名称也大写。

当我运行下面的代码片段时,我看到下面的XML示例,所有标记名称均为小写。我一直在尝试启用/禁用功能,但没有发现任何可以打开/关闭强制使用小写XML标记的功能。

Value of String xml variable below:
ACTUAL OUTPUT:
<root><field1>value</field1><field2>value2<field2><field3>value3<field3><root>

EXPECTED OUTPUT:
<root><Field1>value</Field1><Field2>value2<Field2><Field3>value3<Field3><root>


public class Object1 {
    @XmlElement(name = "Field1", required = true)
    protected String Field1;
    @XmlElement(name = "Field2", required = true)
    protected String Field2;
    @XmlElement(name = "Field3", required = true)
    protected String Field3;
}

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.databind.*;

...


JacksonXmlModule xmlModule = new JacksonXmlModule();
xmlModule.setDefaultUseWrapper(false);
ObjectMapper xmlMapper = new XmlMapper(xmlModule);
xmlMapper.disable( MapperFeature.USE_STD_BEAN_NAMING );

// convert the object into xml string
// object1 is an instance of Object1 above with assigned values 
String xml = xmlMapper.writeValueAsString(object1);

1 个答案:

答案 0 :(得分:2)

这是一个解决方案, 但可能不是您要寻找的答案。

@XmlElement注释替换为@JacksonXmlProperty注释。 使用localName属性设置标签名称。

这里是一个示例: @JacksonXmlProperty(localName = "Field1")