java - 杰克逊没有序列化财产
问题描述
我有以下两个枚举
public enum Action {
ACTION1,
ACTION2,
ACTION3;
}
public enum EntityType {
ENTITYTYPE1,
ENTITYTYPE2;
}
和以下课程
public class EntityIdentityDto implements MetaData {
private String id;
private EntityType entityType;
private Action action;
private Map<String, Object> properties = new HashMap();
public String getId() {
return this.id;
}
public EntityType getEntityType() {
return this.entityType;
}
public Action getAction() {
return this.action;
}
public Map<String, Object> getProperties() {
return this.properties;
}
public void setId(String id) {
this.id = id;
}
public void setEntityType(EntityType entityType) {
this.entityType = entityType;
}
public void setAction(Action action) {
this.action = action;
}
public void setProperties(Map<String, Object> properties) {
this.properties = properties;
}
public EntityIdentityDto() {
}
}
使用 Jackson 2.9.8 序列化为 Json 时,如下所示
public class TestMe {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
EntityIdentityDto entityIdentityDto = new EntityIdentityDto();
entityIdentityDto.setEntityType(EntityType.ENTITYTYPE1);
entityIdentityDto.setAction(Action.ACTION1);
entityIdentityDto.setId("OOO");
String out = objectMapper.writeValueAsString(entityIdentityDto);
System.out.println(out);
}
}
输出是
{"id":"OOO","action":"ACTION1","properties":{}}
我希望 entityType 字段也可以序列化,但这是缺失的。这是我希望看到的
{"id":"OOO","entityType": "ENTITYTYPE1", "action":"ACTION1","properties":{}}
如果我使用 Gson 而不是杰克逊,如下所示
public class TestMe {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
EntityIdentityDto entityIdentityDto = new EntityIdentityDto();
entityIdentityDto.setEntityType(EntityType.SYSTEM);
entityIdentityDto.setAction(Action.SYNC);
entityIdentityDto.setId("OOO");
System.out.println(new Gson().toJson(entityIdentityDto));
}
}
输出符合预期
{"id":"OOO","entityType":"ENTITYTYPE1","action":"ACTION1","properties":{}}
为什么使用 Jackson 生成的 Json 中缺少 entityType 字段?有趣的是,动作被序列化,但 entityType 却没有,即使它们在结构上相同并且在 EntityIdentityDto 中使用相同
解决方案
可能您没有entityType
属性的吸气剂。添加 getter 或使用setVisibility方法:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
也可以看看:
推荐阅读
- angularjs - 在应用程序中访问 angularjs i18n 日期/时间和货币格式
- c# - 如何在 Asp.Net Core 3.1 上创建两类用户
- mongodb - MongoDB - 如何从聚合结果中删除 _id:null?
- unity3d - Unity3d:如何跨多个对象拉伸(或共享)着色器
- c# - 如何检测用户是否在 c# 中摇晃(检测摇晃),
- elasticsearch - ElasticSearch 按查询删除不起作用
- amazon-web-services - 无法在 apache 服务器上启用缓存控制
- php - 在为移动应用程序设计登录时,我是否需要 OAuth 进行用户身份验证?
- authorization - XACML:如何在 long 列表中找到 long(列表包含)
- url - 用于锚标记链接的 IIS 出站规则 URL 重写方案