Jackson XML: how to serialize empty/null collections as empty node

吃可爱长大的小学妹 提交于 2020-01-30 02:40:52

问题


I'm using Jackson XML 2.8.9 and unfortunately I cannot find any way to serialize empty/null collections as empty nodes.

Method responsible for serializing to XML:

protected byte[] toXml(final Collection<ReportView> reports) throws IOException
{
    final XmlMapper mapper = new XmlMapper();
    // place for code which will solve my problem
    return mapper.writerWithDefaultPrettyPrinter().withRootName("report").writeValueAsBytes(reports);
}

I tried to use:

  • serialization inclusion:

    mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
    
  • serialization provider:

    final XmlSerializerProvider provider = new XmlSerializerProvider(new XmlRootNameLookup());
    provider.setNullValueSerializer(new JsonSerializer<Object>()
    {
        @Override
        public void serialize(final Object value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException
        {
            jgen.writeString("");
        }
    });
    mapper.setSerializerProvider(provider);
    
  • Jackson 2.9.0 EMPTY_ELEMENT_AS_NULL feature:

    mapper.configure(FromXmlParser.Feature.EMPTY_ELEMENT_AS_NULL, false);
    

Unfortunately nothing works. Does anybody know how to achieve it?

Test method:

@Test
public void testToXml() throws IOException
{
    final Map<String, Object> payload = new LinkedHashMap<>();
    payload.put("amp", "&");
    payload.put("empty", Collections.emptyList());
    final Date date = new Date();
    final ReportView reportView = new ReportView(payload, date, "system");

    // when
    final byte[] xmlBytes = reportService.toXml(Arrays.asList(reportView));

    // then
    final StringBuilder expected = new StringBuilder();
    expected.append("<report>");
    expected.append("  <item>");
    expected.append("    <payload>");
    expected.append("      <amp>&amp;</amp>");
    expected.append("      <empty></empty>");
    expected.append("    </payload>");
    expected.append("    <timestamp>" + date.getTime() + "</timestamp>");
    expected.append("    <changingUser>system</changingUser>");
    expected.append("  </item>");
    expected.append("</report>");

    final String xmlText = new String(xmlBytes).replace("\n", "").replace("\r", "");
    assertThat(xmlText).isEqualTo(expected.toString());
}

ReportView class:

public class ReportView {
    private final Map<String, Object> payload;
    private final Date timestamp;
    private final String changingUser;

    public ReportView(Map<String, Object> payload, Date timestamp, String changingUser) {
        this.payload = payload;
        this.timestamp= timestamp;
        this.changingUser = changingUser;
    }

    public String getChangingUser() {
        return changingUser;
    }

    public Date getTimestamp() {
        return timestamp;
    }

    public Map<String, Object> getPayload() {
        return payload;
    }
}

I prepared a repository with example code: https://github.com/agabrys/bugs-reports/tree/master/jackson-xml/empty-elements-serialization


EDIT:

I extended the test toXml method and did some code cleanup.

I also tried to create a solution based on Module and SerializerModifier. Unfortunately both ended with failure. I created an issue in jackson-dataformat-xml backlog:

  • NPE after overriding map serializer with custom implementation (XmlBeanSerializerModifier.modifyMapSerializer)

EDIT:

I've got a hint how to solve problem with exception (see NPE after overriding map serializer with custom implementation (XmlBeanSerializerModifier.modifyMapSerializer)) but still it does not solve problem with missing empty/null values.


回答1:


I needed to tackle the same issue, and here's how I got it working:

First I create a serializer that serializes nulls as empty string:

public class NullAsEmptyStringSerializer extends JsonSerializer<Object> {

  static final JsonSerializer<Object> INSTANCE = new NullAsEmptyStringSerializer();

  private static final String EMPTY_STRING = "";
  private final StringSerializer stringSerializer = new StringSerializer();

  @Override
  public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers)
      throws IOException {
    stringSerializer.serialize(EMPTY_STRING, gen, serializers);
  }
}

Then I create a serializer modifier, that overwrites the null serializer of the bean properties with my new serializer:

public class NullToEmptyPropertySerializerModifier extends BeanSerializerModifier {

  @Override
  public List<BeanPropertyWriter> changeProperties(SerializationConfig config,
      BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
    for (BeanPropertyWriter beanProperty : beanProperties) {
      beanProperty.assignNullSerializer(NullAsEmptyStringSerializer.INSTANCE);
    }

    return beanProperties;
  }
}

And finally, I configure the xml mapper to use my modifier:

NullToEmptyPropertySerializerModifier modifier = new NullToEmptyPropertySerializerModifier();
SerializerFactory serializerFactory = BeanSerializerFactory.instance.withSerializerModifier(modifier);
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.setSerializerFactory(serializerFactory);

Trying to see if it's working for strings and objects (Person and Dog are dummy data holder objects):

Dog dog = new Dog("bobby");
Person person = new Person("utku", null, 29, null);
String serialized = xmlMapper.writeValueAsString(person);
System.out.println(serialized);

Gives the following output:

<Person><name>utku</name><address></address><age>29</age><dog></dog></Person>


来源:https://stackoverflow.com/questions/46001938/jackson-xml-how-to-serialize-empty-null-collections-as-empty-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!