package com.tofly.feesapi.common;

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;
import java.text.DecimalFormat;

public class MoneySerializer extends JsonSerializer {
    private static final DecimalFormat decimalFormat = new DecimalFormat("0.00#");

    @Override
    public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (o != null) {
            BigDecimal val;
            if (o instanceof BigDecimal) {
                val = (BigDecimal) o;
            } else {
                val = new BigDecimal(String.valueOf(o));
            }
            jsonGenerator.writeString(decimalFormat.format(val));
        }
    }
}