我试图在 springmvc 中获取一个方法来接受对象的部分 json 字符串,并让 jackson 自动为我反序列化它。 我可以通过创建一个仅包含我想要的属性的临时对象来解决这个问题,或者将其作为字符串传递并使用 Gson 为我对其进行反序列化,但这些感觉很hacky。有什么办法告诉 jackson 该怎么做吗?
这是 Controller 片段:
@RequestMapping(value = "/task",
method = RequestMethod.POST,
consumes="application/json")
public @ResponseBody String postTask(@RequestBody Task task){
if(task.getId() == null){
task.setId(UUID.randomUUID());
}
if(task.getDate_entered() == 0){
task.setDate_entered(System.currentTimeMillis());
}
TaskDao.addTask(task);
return "success";
}
任务,一个基本的 pojo:
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class Task {
private UUID id;
private String name;
private String description;
private long date_entered;
private long finish_by;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
// Rest of the getters and setters
}
如果你不能从我的其他 Spring 相关问题中看出,我有点盲目,无法找出这个问题的正确谷歌查询。
谢谢!
最佳答案
您需要在要忽略序列化和/或反序列化的方法(用于反序列化的 setter 和用于序列化的 getter)或字段上使用 jackson 注释。例如
在您的示例中,如果您不想序列化 description
,那么您可以这样做,
@JsonIgnore
public void setDescription(String description) {
this.description = description;
}
您会发现,在转换后的模型中您将无法获得description
的值。
关于java - 在restful post调用中部分反序列化json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11166224/