字段级别反序列化无法与Jackson合作

时间:2018-04-16 04:34:19

标签: java json spring-mvc json-deserialization jackson-databind

只有在我使用Jackson的字段级反序列化时才会出现400 Bad Request错误。如果我在类级别进行反序列化,那么它可以正常工作。我只想传递用户id而不是整个用户对象,因此字段级反序列化。就我所见,解串器甚至没有被调用。我的代码如下:

模特课:

@Entity
@Table(name = "expense")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Expense implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
private long id;

@Embedded
@AttributeOverrides({
        @AttributeOverride(name = "receiptPicture", column = @Column(name = "receipt_picture"))
})
private ExpenseDetail detail;

@ManyToOne
@JoinColumn(name = "given_by")
@JsonDeserialize(using = ExpenseGivenByDeserializer.class)
private User givenBy;

@ManyToOne
@JoinColumn(name = "given_for")
@JsonIgnore
private House givenFor;

@ManyToMany(cascade = {
        CascadeType.PERSIST,
        CascadeType.MERGE
})
@JoinTable(
        name = "users_approved_expenses",
        joinColumns = {@JoinColumn(name = "expense_id")},
        inverseJoinColumns = {@JoinColumn(name = "user_id")}
)
@JsonIgnore
private List<User> approvedUsers;

@Embedded
@JsonIgnore
private Timer timer;

//....setters and getters

反序列化程序类:

    @Component
    public class ExpenseGivenByDeserializer extends JsonDeserializer<User> {

    @Autowired
    private UserDao userDao;

    @Override
    public User deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        ObjectCodec oc = jp.getCodec();
        JsonNode node = oc.readTree(jp);
        long id = node.get("givenBy").asLong();
        System.out.println("herer");
        return userDao.find(id);
    }
}

我发布这个:

{
    "detail" : {
        "description" : "rice 2 kg",
        "receiptPicture" : "../image/kk.jpg",
        "cost" : "1500"
    },
    "givenBy": 15
}

1 个答案:

答案 0 :(得分:1)

在您的反序列化器中,node是您需要的 值节点 。 (查看node.isValueNode())。

这就够了

JsonNode node = oc.readTree(jp);
long id = node.asLong();
System.out.println("herer"); //prints!

return userDao.find(id);