1

I am using Jackson to convert some simple incoming XML to a simple java class, and back again. Here is my main class:

public static void main (String[] args)
            throws IOException {

        ObjectMapper mapper = new XmlMapper();
        mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);    
        Ussd entries = mapper.readValue(new File("input.xml"), Ussd.class);

        System.out.println(entries.toString());

        mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
        mapper.writeValue(new FileOutputStream(new File("output.xml")), entries);

And an example of xml that I will be dealing with:

<test>
    <type>5</type>
    <msg>Hello World!</msg>
    <premium>
        <cost>12.35</cost>
        <ref>27797740555</ref>
    </premium>
    <msisdn>27231234556</msisdn>
    <sessionid>3</sessionid>
    <network>33</network>
</test>

How do I ensure that the output will be formatted appropriately (I'd ideally like the output to look identical to the input if I simply read it in and write it out)? Currently it returns it all on one line, including a xmlns="" which I would prefer to not be there at all, and telling it to indent the output seems to make no difference (changing the true to false changes nothing). Any glaring issues?

wesrobin
  • 380
  • 1
  • 4
  • 15

1 Answers1

1

This will enable indenting and multi-line output

mapper.enable(SerializationFeature.INDENT_OUTPUT);

If you need more control you'd probably have to provide your own pretty printer with the method SerializationConfig.withDefaeultPrettyPrinter(yourPrinter);

  • This is the correct answer, although six years too late xD. Not sure how you found this question, but thank you. – wesrobin Sep 27 '19 at 07:38