我想要得到和这个链接中提到的结构: 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>
1
Jrue0011 2020-05-19 12:57:31 +08:00
混合使用的话考虑注册 jackson 的 JaxbAnnotationModule 看看,至于有没有效果就不清楚了
https://github.com/FasterXML/jackson-module-jaxb-annotations |
2
Jrue0011 2020-05-19 13:00:46 +08:00
另外上面那个仓库提示转移到 jackson-modules-base 了,但是关于 jaxb 模块的 readme 里的内容还是一样的
|
4
hantsy 2020-05-19 13:41:10 +08:00 1
自己写一个 Searilaizer for **contents**
|
6
chenjian026 2020-05-20 21:25:35 +08:00
|
7
thinkmore OP |