简体   繁体   English

在宁静的post调用中部分反序列化json对象

[英]Partially deserialize a json object in a restful post call

I am trying to get a method in springmvc to accept a partial json string of an object, and have jackson automatically de-serialize it for me. 我试图在springmvc中获得一个方法来接受对象的部分json字符串,并让jackson为我自动反序列化。 I can solve it by making a temporary object with only the attributes I want, or pass it in as a string and use Gson to desearialize it for me, but these feel hacky. 我可以通过仅用我想要的属性制作一个临时对象来解决它,或者将其作为字符串传递并使用Gson对我进行反序列化,但是这些感觉很棘手。 Is there any way to tell jackson how to do it? 有什么办法告诉杰克逊怎么做?

Here is the controller snippet: 这是控制器片段:

@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";
} 

And the task, a basic pojo: 任务是基本的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
}

If you can't tell by my other spring related questions, I'm kind of flying blind, and can't figure out the proper google query for this one. 如果您无法通过其他与春季相关的问题来回答问题,那么我有点盲目,无法找出适合该问题的Google查询。

Thanks! 谢谢!

You need to use @JsonIgnore annotation of jackson on the method (on setter for deserialization and on getter for serialization) or field, for which you want to ignore serialization and/or deserialization. 您需要在要忽略序列化和/或反序列化的方法(用于反序列化的setter和用于序列化的getter)上或字段上使用jackson的@JsonIgnore批注。 eg In your example, if you don't want to serialize description , then you can do, 例如,在您的示例中,如果您不想序列化description ,则可以这样做,

@JsonIgnore
public void setDescription(String description) {
        this.description = description;
 }

And you will see, that you won't get value of description in converted model. 您将看到,在转换后的模型中您将无法获得description价值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM