java Sping Boot 中基于标注的XML编组

33qvvth1  于 2023-02-14  发布在  Java
关注(0)|答案(1)|浏览(98)

在我的Sping Boot 应用程序中,我有以下DTO类

@Data
public clsss Feed {
    private int id;
    private String name;
    private String title;
    
    @Builder
    @XmlRootElement(name = "feeds")
    public static class Feeds {
        @XmlElement(name = "feed")
        @Singular
        private List<Feed> feeds;
    }
}

我的配置类如下

@Component
public class JacksonCustomizer implements Jackson2ObjectMapperBuilderCustomizer {
    @Override
    public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
        jacksonObjectMapperBuilder.modulesToInstall(new JaxbAnnotationModule());
    }
}

DAO类实现如下

public Feeds getAll() {
    String sqlQuery = "SELECT * FROM feed WHERE trash = 0";
    return Feeds.builder().feeds(namedParameterJdbcTemplate.query(sqlQuery, new BeanPropertyRowMapper<>(Feed.class))).build();
}

使用我的REST API,我收到的XML响应如下所示:

<feeds>
    <feed>
        <feed>
            <id>1</id>
            <name>Val1</name>
            <title>Title1</title>
        </feed>
        <feed>
            <id>2</id>
            <name>Val2</name>
            <title>Title2</title>
        </feed>
    </feed>
</feeds>

我想删除作为 Package 器元素出现的<feed>所需的输出如下所示

<feeds>
    <feed>
        <id>1</id>
        <name>Val1</name>
        <title>Title1</title>
    </feed>
    <feed>
        <id>2</id>
        <name>Val2</name>
        <title>Title2</title>
    </feed>
</feeds>
7cwmlq89

7cwmlq891#

在config类中进行更改以将默认 Package 器设置为false。

@Component
public class JacksonCustomizer implements Jackson2ObjectMapperBuilderCustomizer {
    @Override
    public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
        jacksonObjectMapperBuilder.modulesToInstall(new JaxbAnnotationModule());
        jacksonObjectMapperBuilder.defaultUseWrapper(false);  //This was missing before
    }
}

相关问题