springboot使用jackson解析XML

springboot使用jackson解析XML

maven依赖


    com.fasterxml.jackson.dataformat
    jackson-dataformat-xml

一个xml例子



    
    
    
    

    
     

定义好java bean

@Data
@JacksonXmlRootElement(localName = "book")  //root根是book
@JsonIgnoreProperties(ignoreUnknown = true)
public class Book {
    @JacksonXmlElementWrapper(useWrapping = false)    //remote是一个没有list包围的list
    private List remote;
    @JacksonXmlElementWrapper(useWrapping = false)
    private List 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)