gpt4 book ai didi

java - jackson 没有序列化属性(property)

转载 作者:太空宇宙 更新时间:2023-11-04 09:21:43 25 4
gpt4 key购买 nike

我有以下两个枚举

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":{}}

我希望实体类型字段也能序列化,但缺少该字段。这就是我期望看到的

{"id":"OOO","entityType": "ENTITYTYPE1", "action":"ACTION1","properties":{}}

如果我使用 Gson 代替 Jackson,如下所示

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 字段?有趣的是,action 被序列化,但entityType 却没有序列化,尽管它们在结构上相同并且在 EntityIdentityDto 中使用相同。

最佳答案

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

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

另请参阅:

  1. how to specify jackson to only use fields - preferably globally
  2. Jackson – Decide What Fields Get Serialized/Deserialized
  3. Exclude Fields from Serialization in Gson

关于java - jackson 没有序列化属性(property),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58251260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com