我想要得到和这个链接中提到的结构: https://www.coder.work/article/5554449
但是我用 jackson 的注解无法实现。
只使用 jaxb 可以,但是 jaxb 对 CDATA 的支持不行,jackson + jaxb 得不到想要的结果。这两个混合不行。
代码:
@Data
@JacksonXmlRootElement(localName = "articles")
public class Articles {
    private String uuid;
    
    List<ArticleContent> contents;
    public static void main(String[] args) throws JsonProcessingException {
        Articles articles = new Articles();
        articles.setUuid("uuid");
        ArticleContent text1 = new Text("text1");
        ArticleContent video1 = new Video("www.video1.com");
        ArticleContent text2 = new Text("text1");
        ArticleContent video2 = new Video("www.video1.com");
        articles.setContents(Arrays.asList(text1,video1,text2,video2));
        XmlMapper mapper = new XmlMapper();
        System.out.println(mapper.writeValueAsString(articles));
    }
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes({
        @JsonSubTypes.Type(name = "text", value = Text.class),
        @JsonSubTypes.Type(name = "video", value = Video.class)
})
public abstract class ArticleContent {
}
@Data
@AllArgsConstructor
public class Text extends ArticleContent {
    private String content;
}
@Data
@AllArgsConstructor
public class Video extends  ArticleContent{
    String url;
}
pom 依赖:
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
            <version>2.11.0</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
            <scope>provided</scope>
        </dependency>
想要的 xml:
<articles>
   <uuid>uuid</uuid>
   <contents>
     <text>
        <content>text1</content>
     </text>
 
     <video>
        <url>www.video1.com</url>
     </video>
 
     <text>
        <content>text1</content>
     </text>
 
     <video>
        <url>www.video1.com</url>
     </video>
   </contents>
</articles>
上面代码实际得到的 xml:
<?xml version="1.0" encoding="UTF-8"?>
<articles>
   <uuid>uuid</uuid>
   <contents>
      <contents>
         <text>
            <content>text1</content>
         </text>
      </contents>
      <contents>
         <video>
            <url>www.video1.com</url>
         </video>
      </contents>
      <contents>
         <text>
            <content>text1</content>
         </text>
      </contents>
      <contents>
         <video>
            <url>www.video1.com</url>
         </video>
      </contents>
   </contents>
</articles>
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.