问题
In Spring/Hibernate project, in my entity class I have:
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;
}
}
My serializer 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");
}
}
I expect to get JSON with "bank_transaction_date": "blabla"
.
Instead, I get it with "bank_transaction_date": null
. I also notice, that if I set a breakpoint in my serializer, debugger is never stopping there, so it is probably not used.
What's wrong?
回答1:
The answer was very simple: bankTransactionDate
was null
, and it turns out, that for null
values serializer is not called :)
Once I filled database with values, serializer started to work and gave me "bank_transaction_date": "blabla"
.
来源:https://stackoverflow.com/questions/35342323/jsonserialize-not-working