alibaba / alibaba/fastjson2

[FEATURE] 当对象中含有BigInteger类型的字段时,没有办法在全局设置中强制转换String

Open
#3,870 38 comments 0 reactions 0 assignees View on GitHub
enhancement
Dominant language
Java
Stars
4.4k
Forks
613
Avg merge
1d 22h
Merged PRs (30d)
6

Description

```
@Data
public static class test {
int a = 1;
Integer b = 2;
long c = 1;
Long d = 1123123213213123213L;

//@JSONField(serializeUsing = BigIntegerToStringSerializer.class)
BigInteger e = new BigInteger("123");

}

public static void main(String[] args) {
FastJsonConfig jsonConfig = new FastJsonConfig();
jsonConfig.setWriterFeatures();

ObjectWriterProvider objectWriterProvider=new ObjectWriterProvider();
objectWriterProvider.register(Long.class, ObjectWriters.ofToString(Object::toString));
JSONWriter.Context context= JSONFactory.createWriteContext(objectWriterProvider);

JSON.config(JSONWriter.Feature.WriteLongAsString);

//JSON.config(JSONWriter.Feature.WriteNonStringValueAsString);
//JSON.config(JSONWriter.Feature.BrowserCompatible);

JSON.register(Long.class, ObjectWriters.ofToString(Object::toString));
JSON.register(Long.TYPE, ObjectWriters.ofToString(Object::toString));
JSON.register(BigInteger.class, ObjectWriters.ofToString(Object::toString));

String json1 = JSONObject.toJSONString(new test());

log.info(json1);
}
```

输出结果{"a":1,"b":2,"c":"1","d":"1123123213213123213","e":123}

JSONWriter.Feature.WriteNonStringValueAsString和JSONWriter.Feature.BrowserCompatible虽然能部分实现,但是会引入更多的问题,一个会强制把所有的对象都转为字符串,另一个则是为了适配浏览器兼容只会把超过9007199254740991和小于-9007199254740991的转为string,而且空值还会按 JSON 标准输出 null/undefined

看了下源码,序列化时最终会进入JSONWriterUTF16.writeBigInt方法,其中有个isWriteAsString来判断是否转为String

protected static boolean isWriteAsString(BigDecimal value, long features) {
return (features & MASK_WRITE_NON_STRING_VALUE_AS_STRING) != 0
|| ((features & MASK_BROWSER_COMPATIBLE) != 0 && !isJavaScriptSupport(value));
}

只有JSONWriter.Feature.WriteNonStringValueAsString或者JSONWriter.Feature.BrowserCompatible并且超出了9007199254740991范围才会转String

希望能增加一个JSONWriter.Feature.WriteBigIntegerAsString的枚举和判断条件,或者有其他的方法请告知一下,不胜感激

Contributor guide

Open the contributing guide

Research direction

Start in JSONWriterUTF16.writeBigInt and inspect the isWriteAsString logic described in the issue, along with the JSONWriter.Feature definitions. Add the requested global BigInteger-as-string behavior without changing the broader WriteNonStringValueAsString or BrowserCompatible semantics; done means BigInteger fields serialize as strings when the new setting is enabled.

Written by the indexing model from the issue text.

Assessment

Tech stack
java, json
Domain
backend
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Clearly specified
Newbie friendliness
64/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.