首页 > 解决方案 > 杰克逊没有序列化财产

问题描述

我有以下两个枚举

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 中使用相同

标签: javajsonjackson2

解决方案


可能您没有entityType属性的吸气剂。添加 getter 或使用setVisibility方法:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

也可以看看:

  1. 如何指定杰克逊只使用字段 - 最好是全局
  2. Jackson – 决定哪些字段被序列化/反序列化
  3. 从 Gson 中的序列化中排除字段

推荐阅读