@JsonSerialize 不工作

@JsonSerialize not working

在 Spring/Hibernate 项目中,在我的实体 class 中,我有:

package klab.finance.main.entity;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import klab.backend.entity.postgres.base.BaseEntity;
import klab.backend.utils.DateTimeUtils;
import klab.backend.utils.JsonDateTime;
import klab.backend.utils.json.LocalDateTimeToTimestampDeserializer;
import klab.backend.utils.json.TimestampToLocalDateTimeSerializer;
import org.hibernate.annotations.Where;
import org.joda.time.LocalDateTime;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name="transactions")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Transaction extends BaseEntity {

    private Long bankTransactionDate;

    @Column(name="bank_transaction_date")
    @JsonSerialize(using = TimestampToLocalDateTimeSerializer.class)
    public Long getBankTransactionDate(){
        return bankTransactionDate;
    }

    @JsonDeserialize(using = LocalDateTimeToTimestampDeserializer.class)
    public void setBankTransactionDate(Long bankTransactionDate){
        this.bankTransactionDate=bankTransactionDate;
    }
}

我的序列化器class:

package klab.backend.utils.json;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import klab.backend.entity.postgres.base.BaseEntity;
import klab.backend.utils.DateTimeUtils;
import org.joda.time.LocalDateTime;

import java.io.IOException;

public class TimestampToLocalDateTimeSerializer extends JsonSerializer<Long> {

    @Override
    public void serialize(Long value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
            throws IOException {

        jsonGenerator.writeString("blabla");
    }
}

我希望通过 "bank_transaction_date": "blabla" 获得 JSON。

相反,我用 "bank_transaction_date": null 得到它。我还注意到,如果我在我的序列化程序中设置断点,调试器永远不会停在那里,所以它可能不会被使用。

怎么了?

答案很简单:bankTransactionDatenull,事实证明,对于 null 值序列化器没有被调用 :)

一旦我用值填充了数据库,序列化程序就开始工作并给了我 "bank_transaction_date": "blabla"