!192 修复JSONUtil.toBean精度丢失

Merge pull request !192 from shiguanghuixiao/v5-dev
This commit is contained in:
Looly 2020-10-11 13:20:19 +08:00 committed by Gitee
commit 6ea9912fd4
2 changed files with 71 additions and 4 deletions

View File

@ -9,6 +9,7 @@ import cn.hutool.core.util.StrUtil;
import java.io.IOException;
import java.io.Writer;
import java.math.BigDecimal;
import java.time.temporal.TemporalAccessor;
import java.util.Calendar;
import java.util.Collection;
@ -158,10 +159,7 @@ final class InternalJSONUtil {
if ((b >= '0' && b <= '9') || b == '-') {
try {
if (string.indexOf('.') > -1 || string.indexOf('e') > -1 || string.indexOf('E') > -1) {
double d = Double.parseDouble(string);
if (false == Double.isInfinite(d) && false == Double.isNaN(d)) {
return d;
}
return new BigDecimal(string);
} else {
Long myLong = new Long(string);
if (string.equals(myLong.toString())) {

View File

@ -10,8 +10,10 @@ import cn.hutool.json.test.bean.UserC;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JSONUtilTest {
@ -124,6 +126,15 @@ public class JSONUtilTest {
// Assert.assertEquals("{\"age\":18,\"gender\":\"\"}", user.getProp());
}
@Test
public void toBeanTest3() {
// 测试数字类型精度丢失的情况
String number = "1234.123456789123456";
String jsonString = "{\"create\":{\"details\":[{\"price\":" + number + "}]}}";
WebCreate create = JSONUtil.toBean(jsonString, WebCreate.class);
Assert.assertEquals(number,create.getCreate().getDetails().get(0).getPrice().toString());
}
@Test
public void putByPathTest() {
JSONObject json = new JSONObject();
@ -161,4 +172,62 @@ public class JSONUtilTest {
final JSONObject jsonObject = JSONUtil.parseObj(json);
Assert.assertEquals("12.00", jsonObject.getBigDecimal("test").setScale(2).toString());
}
class WebCreate {
private Create create;
@Override
public String toString() {
return "WebCreate{" +
"create=" + create +
'}';
}
public void setCreate(Create create) {
this.create = create;
}
public Create getCreate() {
return create;
}
}
class Create {
@Override
public String toString() {
return "Create{" +
"details=" + details +
'}';
}
private List<Detail> details;
public void setDetails(List<Detail> details) {
this.details = details;
}
public List<Detail> getDetails() {
return details;
}
}
class Detail {
private BigDecimal price;
public void setPrice(BigDecimal price) {
this.price = price;
}
@Override
public String toString() {
return "Detail{" +
"price=" + price +
'}';
}
public BigDecimal getPrice() {
return price;
}
}
}