Prevent Jackson XML mapper from adding wstxns to namespaces

后端 未结 2 1198
孤独总比滥情好
孤独总比滥情好 2021-01-16 11:07

When serialising objects to XML and specifying namespaces for properties using @JacksonXmlRootElement(namespace = \"http://...\") Jackson will append or prepen

2条回答
  •  悲哀的现实
    2021-01-16 11:55

    This seems to be the missing piece. It allows you to set the prefix and namespace.

       static class NamespaceXmlFactory extends XmlFactory {
    
        private final String defaultNamespace;
        private final Map prefix2Namespace;
    
        public NamespaceXmlFactory(String defaultNamespace, Map prefix2Namespace) {
            this.defaultNamespace = Objects.requireNonNull(defaultNamespace);
            this.prefix2Namespace = Objects.requireNonNull(prefix2Namespace);
        }
    
        @Override
        protected XMLStreamWriter _createXmlWriter(IOContext ctxt, Writer w) throws IOException {
            XMLStreamWriter2 writer = (XMLStreamWriter2)super._createXmlWriter(ctxt, w);
            try {
                writer.setDefaultNamespace(defaultNamespace);
                writer.setPrefix("xsi", "http://www.w3.org/2001/XMLSchema-instance");
                for (Map.Entry e : prefix2Namespace.entrySet()) {
                    writer.setPrefix(e.getKey(), e.getValue());
                }
            } catch (XMLStreamException e) {
                StaxUtil.throwAsGenerationException(e, null);
            }
            return writer;
        }
    }
    

    The only remaining issue I have is

        @JacksonXmlProperty(localName = "@xsi.type", isAttribute = true, namespace = "http://www.w3.org/2001/XMLSchema-instance")
    @JsonProperty("@xsi.type")
    private String type;
    

    Creates the following output:

    Still trying to resolve how to make it be xsi:type="networkObjectGroupDTO" instead.

提交回复
热议问题