如何像fastjson1一样,在使用@JSONField注解时,获取注解上的format属性的值 #2400
Open
Description
请描述您的问题
询问有关本项目的使用和其他方面的相关问题。
在fastjson1中,继承ContextObjectSerializer,我可以通过BeanContext context获取JSONField注解中的format字段,类似
@JSONField(serializeUsing = CustomerBigDecimalCodec.class, format = "#,###.####")
在CustomerBigDecimalCodec中,可以对不同字段实现不同精度的序列化,但是在fastjson2中。如何实现类似的需求,通过继承ObjectWriter
,JSONWriter无法获取JSONField注解上format的值
public class CustomerBigDecimalCodec extends BigDecimalCodec implements ContextObjectSerializer {
@Override
public void write(JSONSerializer serializer, Object object, BeanContext context) throws IOException {
SerializeWriter out = serializer.out;
if (object == null) {
out.writeString("0.00");
return;
}
String format = context.getFormat();
String[] split = format.split(":");
if (split.length > 1) {
BigDecimal number = ((BigDecimal) object).setScale(Integer.parseInt(split[1]), RoundingMode.HALF_UP);
DecimalFormat formatter = new DecimalFormat(split[0]);
out.writeString(formatter.format(number));
return;
}
DecimalFormat decimalFormat = new DecimalFormat(format);
out.writeString(decimalFormat.format(object));
}
}