package cn.quantgroup.customer.util;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.math.BigDecimal;

/**
 * 在字段或get上加:
 * <b>@JsonSerialize(using = MoneySerializer.class)</b>
 * @author Jie.Feng
 * @date 2018/8/28
 */
public class MoneySerializer extends JsonSerializer<BigDecimal> {
    /**
     * Method that can be called to ask implementation to serialize
     * values of type this serializer handles.
     *
     * @param value       Value to serialize; can <b>not</b> be null.
     * @param gen         Generator used to output resulting Json content
     * @param serializers Provider that can be used to get serializers for
     */
    @Override
    public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if(value == null)
            gen.writeString("0.00");
        else
            gen.writeString(value.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
    }
}
