@JsonSerialize无法正常工作

时间:2016-02-11 14:41:11

标签: java json spring jackson jsonserializer

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

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

我的序列化程序类:

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得到它。我还注意到,如果我在序列化程序中设置断点,调试器永远不会停在那里,所以可能没有使用它。

出了什么问题?

1 个答案:

答案 0 :(得分:0)

答案非常简单:bankTransactionDatenull,事实证明,null值不会调用序列化程序:)

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