BigDecimal类型序列化

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParsePosition;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.jackson.JsonComponent;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
/**
 * BigDecimal类型序列化
 */
@JsonComponent
public class BigDecimalDeSerializer extends JsonDeserializer<BigDecimal> {

	@Override
	public BigDecimal deserialize(JsonParser jsonParser, DeserializationContext ctxt)
			throws IOException, JsonProcessingException {
		  return this.readStrAsBigDecimalAndCheckFormat(jsonParser.getText());
	}

	public BigDecimal readStrAsBigDecimalAndCheckFormat(String str) {
		DecimalFormat format = new DecimalFormat();
		format.setParseBigDecimal(true);
		ParsePosition position = new ParsePosition(0);
		BigDecimal parse = (BigDecimal) format.parse(str, position);
		if (str.length() == position.getIndex()) {
			return parse;
		}
		return null;

	}

}

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Objects;

import org.springframework.boot.jackson.JsonComponent;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

/**
 * BigDecimal类型序列化
 * 
 *
 */
@JsonComponent
public class BigDecimalSerializer extends JsonSerializer<BigDecimal> implements ContextualSerializer {

	private String format = ",###.##";

	@Override
	public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty)
			throws JsonMappingException {
		if (beanProperty != null) {
			if (Objects.equals(beanProperty.getType().getRawClass(), BigDecimal.class)) {
				BigDecimalSerializer bigDecimalSerializer = new BigDecimalSerializer();
				return bigDecimalSerializer;
			}

			return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
		}
		return serializerProvider.findNullValueSerializer(beanProperty);
	}

	@Override
	public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
		gen.writeString(new DecimalFormat(format).format(value));

	}

}

你可能感兴趣的:(java,java,开发语言)