Java-POJO序列化Jackson 2.0

时间:2019-02-08 21:56:31

标签: java json serialization jackson deserialization

我整天都在扫描堆栈溢出,但是没有找到可行的解决方案来解决我的问题。

我有一个带有原始类型和嵌套对象的pojo。例如...

@JsonIgnoreProperties({"duration", "errorCode", "haveFieldsChanged", 
"serviceRequestToken", "storedProcDuration"}) // Abstract Base Class 
 properties
class Bus extends AbstractBaseClass implements Serializable{

    @JsonIgnore
    private static final long serialVersionId = 1;

    @JsonProperty("name")
    String name;

    @JsonProperty("id")
    int id;

    @JsonProperty("students")
    List<Student> students; // Nested Objects

    @JsonProperty("employer")
    Employer employer; //Nested object

    // Getters and setters - none are annotated

@JsonRootName(value = "student")
class Student implements Serializable{
    // student fields
}

@JsonRootName(value = "statusType")
class Employer implements Serializable{

    @JsonProperty("id")
    int id;
}

当我序列化Bus对象时,jackson可以为名称,id和我的学生列表创建正确的结构。但是,它将完全跳过Employer,而将其保留在json中。见下文。

{
  "name":"Sean",
  "id": 1,
  "students":[student objects...]
}

我尝试了@ JsonProperty,@ JsonSerialize(as = Employer.class),我尝试为雇主对象构建地图。我觉得我已经用尽了大多数选择。有什么我想念的吗?

我在尝试其他注释时遇到了堆栈溢出异常。感谢您能提供的任何帮助。

我将@JsonProperty添加到字段中的原因是为了帮助实现反序列化。我认为这可能是序列化的根本原因,但我不确定。

序列化实现

private String serializeBus(Bus bus) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    String json = null;
    try {
        json = mapper.writeValueAsString(bus);
    } catch (JsonProcessingException e) {
        logger.error("Error serializing bus");
        throw new Exception(e);
    }
    return json;
}

谢谢!

1 个答案:

答案 0 :(得分:0)

因此,如果您共享代码不可行,那么我将您的示例放在一个小沙盒项目中:https://github.com/mle-enso/stackoverflow 它目前与Spring Boot 2.1一起运行,但是将托管的Jackson版本降级为2.6.1不会产生负面影响。

也许您可以通过简单的mvn clean verify或手动运行de.mle.stackoverflow.jackson.BusSerializerTest来尝试该项目,以在此处进一步探讨此问题。