javacollectionsjaxbmarshalling

Jaxb marshalling with nillable = true on collection do not work


I've got DTO:

@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MyData {

    private String payload;

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    @XmlRootElement(name = "return")
    @XmlAccessorType(XmlAccessType.FIELD)
    public static class PayloadSchema {

        @XmlElement(name = "foos", nillable = true)
        private List<Foo> foos;
        @XmlElement(name = "code")
        private String code;

    }

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    @XmlAccessorType(XmlAccessType.FIELD)
    public static class Foo {

        @XmlElement(name = "number")
        private String number;
    }

}

I want to get <ns:foos xsi:nil="true"/> if the foos set to null value. I've tried to change List_Foo to simple String and it works as expected. So, it looks like a problem with collections. I'm using default implementation of marshaller:

public static String toXmlString(Object dto) {
        try {
            JAXBContext context = JAXBContext.newInstance(dto.getClass());
            Marshaller marshaller = context.createMarshaller();
            StringWriter sw = new StringWriter();
            marshaller.marshal(dto, sw);
            return sw.toString();
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

What should I change to make this works as expected? Thanks in advance!


Solution

  • Add @XmlElementWrapper annotation to your list and it will work as you expecting:

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    @XmlRootElement(name = "return")
    @XmlAccessorType(XmlAccessType.FIELD)
    public static class PayloadSchema {
    
        @XmlElementWrapper(name = "foos", nillable = true)
        @XmlElement(name = "foo")
        private List<Foo> foos;
        
        @XmlElement(name = "code")
        private String code;
    
    }