ras*_*orp 6 java xml json jackson
我有一个类,我使用Jackson对JSON,XML进行序列化/反序列化.
public class User {
Integer userId;
String name;
Integer groupId;
...
}
Run Code Online (Sandbox Code Playgroud)
我想在进行xml处理时忽略groupId,所以我的XML不会包含它:
<User>
<userId>...</userId>
<name>...</name>
</User>
Run Code Online (Sandbox Code Playgroud)
但是JSON会:
{
"userId":"...",
"name":"...",
"groupId":"..."
}
Run Code Online (Sandbox Code Playgroud)
我知道@JsonIgnore可以兼用,但我只想在xml中忽略它.
我知道可用于执行此操作的混合注释(/sf/answers/1603477641/),但我认为应该有一个简单的注释来执行此操作,但无法找到它.杰克逊的文档(至少对我而言)并不像我想要找到这些东西时那样好.
杰克逊不支持开箱即用.但是您可以使用Jackson json视图或创建自定义注释,该注释将@JsonIgnore通过注释interospector为XML映射器进行解释.
这是一个例子:
public class JacksonXmlAnnotation {
@Retention(RetentionPolicy.RUNTIME)
public static @interface JsonOnly {
}
@JacksonXmlRootElement(localName = "root")
public static class User {
public final Integer userId;
public final String name;
@JsonOnly
public final Integer groupId;
public User(Integer userId, String name, Integer groupId) {
this.userId = userId;
this.name = name;
this.groupId = groupId;
}
}
public static class XmlAnnotationIntrospector extends JacksonXmlAnnotationIntrospector {
@Override
public boolean hasIgnoreMarker(AnnotatedMember m) {
return m.hasAnnotation(JsonOnly.class) || super.hasIgnoreMarker(m);
}
}
public static void main(String[] args) throws JsonProcessingException {
User user = new User(1, "John", 23);
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.setAnnotationIntrospector(new XmlAnnotationIntrospector());
ObjectMapper jsonMapper = new ObjectMapper();
System.out.println(xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(user));
System.out.println(jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(user));
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
<root>
<userId>1</userId>
<name>John</name>
</root>
{
"userId" : 1,
"name" : "John",
"groupId" : 23
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5696 次 |
| 最近记录: |