【发布时间】:2019-02-08 21:56:30
【问题描述】:
我整天都在扫描堆栈溢出,但没有找到可行的解决方案来解决我的问题。
我有一个具有原始类型和嵌套对象的 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;
}
谢谢!
【问题讨论】:
-
我用 getter 和 setter 创建了类似的结构,它也为我打印了
employer。您是否使用任何注释或其他类型的配置?您使用哪个版本的库? -
您问题中的所有代码都非常好,而不是员工未序列化的原因。您能否向我们展示一个 Github 存储库或与您序列化总线对象的方式类似的东西?
-
employer可以为空吗? -
我在所有课程中都有 getter 和 setter。我使用了一些注释。请参考我上面的示例代码。 @MichałZiober
-
不幸的是,该代码是专有的,因此无法将其推送到 github。 @mle
标签: java json serialization jackson deserialization