简体   繁体   中英

How to serialize an object with xml string as field to xml and set property name for this field (Jackson Object Mapper)?

I'm trying to serialize an object to xml with Object Mapper. An object's field is a xml string itself. I use @JsonRawValue so Jackson won't escape xml charactets, like < or /> . But, with @JsonRawValue Jackson ignores @JacksonXmlProperty annotation, and writes the string directly, omitting property name.

So this code:

public class Example {
   @JsonRawValue
   @JacksonXmlProperty(localName = "SOME_NAME")
   private String xml = "<xmlExample>123</xmlExample>";
}

produces:

<Example> <xmlExample>123</xmlExample> </Example>

When i want:

<Example>
    <SOME_NAME> <xmlExample>123</xmlExample> </SOME_NAME>
</Example>

So the proplem is that @JacksonXmlProperty doesn't work with @JsonRawValue. And i don't know how to get rid of @JsonRawValue, because without this annotation, Jackson escapes some xml characters.

UPDATE: Output generation code:

Example example = new Example();
String s = new XmlMapper().vriteValueAsString(example);

Try

 import com.fasterxml.jackson.databind.SerializationFeature;
 import com.fasterxml.jackson.dataformat.xml.XmlMapper;

 public static void main(String[] args) {

        try {
            Example example = new Example();
            XmlMapper xmlMapper = new XmlMapper();
            xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);
            String xmlString = xmlMapper.writeValueAsString(example);
            System.out.println(xmlString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Output:

<Example><SOME_NAME><xmlExample>123</xmlExample></SOME_NAME></Example>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM