1

Imagine a situation when you have a model in Java, and you have to serialize it both to XML and CSV.

I am using Jaxb Marshaller for XML and Jackson's CsvMapper (ObjectMapper) for CSV.

Since the formats are slightly different, I want Jackson's CsvMapper to ignore Jaxb related annotations like @XmlType or @XmlElement. Because Jackson is getting information/considers xml annotations as well and it leads to wrong result.

How can I do it?

funtik
  • 1,688
  • 3
  • 11
  • 27
  • How do you create `CsvMapper` instance? `Jackson` by default does not recognize `JaxB` annotations. To recognize them `Jackson` requires [jackson-module-jaxb-annotations](https://github.com/FasterXML/jackson-module-jaxb-annotations) module. – Michał Ziober Aug 20 '20 at 14:48
  • no, `Jackson` does recognize `Jaxb` annotations by default, and some of them have higher precedence that its own annotations – funtik Aug 21 '20 at 07:19
  • Do you use `Jackson` together with `Spring Boot` or something similar which could automatically register `JAXB` module? How do you create `CsvMapper` object? Could you create a simple example which could reproduce this error? – Michał Ziober Aug 21 '20 at 07:40
  • hmm...we do use Spring Boot! here's the code for csv mapper: `CsvMapper csvMapper = new CsvMapper();` `csvMapper.findAndRegisterModules();` `csvMapper.enable(CsvParser.Feature.WRAP_AS_ARRAY);` `csvMapper.setTimeZone(TimeZone.getTimeZone(getApplicationZoneId()));` `csvMapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true));` `CsvSchema schema = csvMapper.schemaFor(clazz)` ` .withColumnSeparator('|')` ` .withQuoteChar('"')` ` .withNullValue("\"\"");` is there any way i can unregister jaxb module? – funtik Aug 21 '20 at 07:50
  • 1
    `csvMapper.findAndRegisterModules();` - this line tries to register modules available on class path. You can remove it and `JAXB` module will be ignored. Manually register only this modules you need. – Michał Ziober Aug 21 '20 at 09:27
  • 1
    you were right! you should put it as an answer! thanks! – funtik Aug 21 '20 at 11:00

1 Answers1

1

This is the way how you probably create new CsvMapper:

CsvMapper csvMapper = new CsvMapper();
csvMapper.findAndRegisterModules();

findAndRegisterModules method invokes findModules which documentation says:

Method for locating available methods, using JDK ServiceLoader facility, along with module-provided SPI.

So, probably you have jackson-module-jaxb-annotations module on class path and this is why CsvMapper recognizes JAXB annotations.

To fix it, you need to remove invocation of this method findAndRegisterModules and register only these modules you needed.

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146