Skip to content

Commit

Permalink
fix #2558 (#2559)
Browse files Browse the repository at this point in the history
fix org.bson.types.Decimal128 to Double, for issue #2558
  • Loading branch information
ocean23 committed May 11, 2024
1 parent 45cc6b3 commit 7f22132
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
17 changes: 17 additions & 0 deletions core/src/main/java/com/alibaba/fastjson2/util/TypeUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -1522,6 +1522,23 @@ public static <T> T cast(Object obj, Class<T> targetClass, ObjectReaderProvider
break;
}
}
// fix org.bson.types.Decimal128 to Double
String objClassName = obj.getClass().getName();
if (objClassName.equals("org.bson.types.Decimal128") && targetClass == Double.class) {
ObjectWriter objectWriter = JSONFactory
.getDefaultObjectWriterProvider()
.getObjectWriter(obj.getClass());
if (objectWriter instanceof ObjectWriterPrimitiveImpl) {
Function function = ((ObjectWriterPrimitiveImpl<?>) objectWriter).getFunction();
if (function != null) {
Object apply = function.apply(obj);
Function DecimalTypeConvert = provider.getTypeConvert(apply.getClass(), targetClass);
if (DecimalTypeConvert != null) {
return (T) DecimalTypeConvert.apply(obj);
}
}
}
}

ObjectWriter objectWriter = JSONFactory
.getDefaultObjectWriterProvider()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.alibaba.fastjson2.issues_2500;

import com.alibaba.fastjson2.util.TypeUtils;
import org.bson.types.Decimal128;
import org.junit.jupiter.api.Test;

import java.math.BigDecimal;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class Issue2558 {
@Test
public void test() {
BigDecimal decimal = new BigDecimal("123.45");
Decimal128 decimal128 = new Decimal128(decimal);
Double doubleValue = decimal.doubleValue();

assertEquals(
doubleValue,
TypeUtils.cast(decimal128, Double.class)
);
}
}

0 comments on commit 7f22132

Please sign in to comment.