如何像fastjson1一样,在使用@JSONField注解时,获取注解上的format属性的值
- Dominant language
- Java
- Stars
- 4.4k
- Forks
- 613
- Avg merge
- 1d 22h
- Merged PRs (30d)
- 6
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));
}
}
```
Contributor guide
Research direction
Start by comparing fastjson1's ContextObjectSerializer and BeanContext behavior with fastjson2's ObjectWriter and JSONWriter APIs, focusing on how JSONField annotations are handled. The issue mentions BigDecimalCodec and the annotation's format value but names no source files or tests. Done means establishing a supported way to access the per-field format and validating it with the shown BigDecimal serialization case.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- java
- Domain
- backend
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100