Skip to content

Commit 7f22132

Browse files
authored
fix #2558 (#2559)
fix org.bson.types.Decimal128 to Double, for issue #2558
1 parent 45cc6b3 commit 7f22132

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

core/src/main/java/com/alibaba/fastjson2/util/TypeUtils.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1522,6 +1522,23 @@ public static <T> T cast(Object obj, Class<T> targetClass, ObjectReaderProvider
15221522
break;
15231523
}
15241524
}
1525+
// fix org.bson.types.Decimal128 to Double
1526+
String objClassName = obj.getClass().getName();
1527+
if (objClassName.equals("org.bson.types.Decimal128") && targetClass == Double.class) {
1528+
ObjectWriter objectWriter = JSONFactory
1529+
.getDefaultObjectWriterProvider()
1530+
.getObjectWriter(obj.getClass());
1531+
if (objectWriter instanceof ObjectWriterPrimitiveImpl) {
1532+
Function function = ((ObjectWriterPrimitiveImpl<?>) objectWriter).getFunction();
1533+
if (function != null) {
1534+
Object apply = function.apply(obj);
1535+
Function DecimalTypeConvert = provider.getTypeConvert(apply.getClass(), targetClass);
1536+
if (DecimalTypeConvert != null) {
1537+
return (T) DecimalTypeConvert.apply(obj);
1538+
}
1539+
}
1540+
}
1541+
}
15251542

15261543
ObjectWriter objectWriter = JSONFactory
15271544
.getDefaultObjectWriterProvider()
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.alibaba.fastjson2.issues_2500;
2+
3+
import com.alibaba.fastjson2.util.TypeUtils;
4+
import org.bson.types.Decimal128;
5+
import org.junit.jupiter.api.Test;
6+
7+
import java.math.BigDecimal;
8+
9+
import static org.junit.jupiter.api.Assertions.assertEquals;
10+
11+
public class Issue2558 {
12+
@Test
13+
public void test() {
14+
BigDecimal decimal = new BigDecimal("123.45");
15+
Decimal128 decimal128 = new Decimal128(decimal);
16+
Double doubleValue = decimal.doubleValue();
17+
18+
assertEquals(
19+
doubleValue,
20+
TypeUtils.cast(decimal128, Double.class)
21+
);
22+
}
23+
}

0 commit comments

Comments
 (0)