美文网首页
springboot使用jackson解析XML

springboot使用jackson解析XML

作者: 金琥 | 来源:发表于2020-07-06 19:55 被阅读0次

    springboot使用jackson解析XML

    maven依赖

    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-xml</artifactId>
    </dependency>
    

    一个xml例子

    <?xml version="1.0" encoding="UTF-8"?>
    <book>
        <remote name="java" url="http://bookstack.cn/" />
        <remote name="c" url="http://jianshu.cn/" />
        <remote name="javascript" url="http://www.w3school.com.cn/" />
        <default name="java" />
    
        <project name="Java核心技术" author="Cay S. Horstmann" />
        <project name="Learning Spring Boot 2.0" author="Greg L. Turnquist" /> 
    </book>
    

    定义好java bean

    @Data
    @JacksonXmlRootElement(localName = "book")  //root根是book
    @JsonIgnoreProperties(ignoreUnknown = true)
    public class Book {
        @JacksonXmlElementWrapper(useWrapping = false)    //remote是一个没有list包围的list
        private List<Remote> remote;
        @JacksonXmlElementWrapper(useWrapping = false)
        private List<Project> project;
        @JacksonXmlProperty(localName = "default")   //default是保留字,不能作为bean名称,因此用localname指定
        private DefaultEle defaultvalue;
    }
    

    定义下层的bean

    @Data
    @JsonIgnoreProperties(ignoreUnknown = true)   //忽略掉xml里不关注的element
    public class Project {
        @JacksonXmlProperty(isAttribute = true)   //name是project的attribute属性,不是value
        private String name;
    }
    

    java代码

            InputStream input = Main.class.getResourceAsStream("/book.xml");
            JacksonXmlModule module = new JacksonXmlModule();
            XmlMapper mapper = new XmlMapper(module);
            try {
                Book book = mapper.readValue(input, Book.class);
                System.out.println(book.getProject().get(0).getName());
            } catch (IOException e) {
                e.printStackTrace();
            }
    

    相关文章

      网友评论

          本文标题:springboot使用jackson解析XML

          本文链接:https://www.haomeiwen.com/subject/nybgqktx.html