JAXB 无法处理包含白色 space 到 java.net.URI 映射的 XML 元素

JAXB can not handle XML element containing white space to java.net.URI mapping

我有 XML 如下:

<repository>
<location>/home/username whitespace/somedir</location>
</repository>

我正在使用 JAXB 将其解组为带 JAXB 注释的 Bean。 "location" XML 元素映射到 java.net.URI class。 问题是当 location 包含白色 space 时,JAXB(或者可能是底层的 XML 解析器)无法处理这个并且 location 被设置为 null。没有 UnmarshalException 或任何东西,只是用 null 方法参数调用 setLocation(URI loc)

没有白色 space 的 URI 当然可以正常工作。 问题是我无法真正将 RepositoryDTO 更改为具有 String location; 字段。

你能告诉我这里有哪些选择吗?

我应该查看 URLEncode,然后解码上述 location 字段吗?

顺便说一句,这是一个 REST/Jersey 用例,虽然显然罪魁祸首在于 JAXB/XML 解析器...

    public class Whitespace {

    public static void main(String[] args) throws JAXBException {
        String xml = "<repository><location>/home/username whitespace/somedir</location></repository>";

        Unmarshaller createUnmarshaller = JAXBContext.newInstance(RepositoryDTO.class).createUnmarshaller();
        RepositoryDTO repositoryInfo = (RepositoryDTO) createUnmarshaller.unmarshal(new StringReader(xml));
        System.out.println(repositoryInfo.getLocation());

    }

    @XmlRootElement(name = "repository")
    static public class RepositoryDTO {
        private URI location;

        @XmlElement
        public URI getLocation() {
            return location;
        }

        public void setLocation(URI loc) {
            this.location = loc;
        }

    }
}

尝试使用白色的标准 URL 编码space(将 XML 元素内的 space 替换为 %20)

你可以使用这个适配器

import java.net.URI;
import java.net.URISyntaxException;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class UriAdapter extends XmlAdapter<String, URI> {

    public URI unmarshal(String s) {
        if(s != null){
            try {
                return new URI(s.replace(" ", "%20"));
            } catch (URISyntaxException e) {
            }
        }
        return null;
    }

    public String marshal(URI uri) {
        return uri.getPath();
    }
}

这样

@XmlJavaTypeAdapter(UriAdapter.class)
protected URI location;