import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import java.util.Date;
public class MainClass {
public static void main(String[] args) {
Order order = new Order();
order.setCreateTime(new Date());
System.out.println(order);
String s = JSON.toJSONString(order);
System.out.println(s);
}
}
@Data
class Order{
//使用自定义的对象序列化器
@JSONField(serializeUsing = DateToLong.class)
private Date createTime;
}
自定义对象序列化器
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Date;
public class DateToLong implements ObjectSerializer {
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
if(object instanceof Date){
SerializeWriter out = serializer.out;
long time=((Date) object).getTime();
out.writeLong(time);
}
}
}