dromara / hutool

🍬A set of tools that keep Java sweet.
https://hutool.cn
Other
28.91k stars 7.48k forks source link

JSONUtil.toBean时,如果Bean没有任何字段,会报错ConvertException: Can not Converter from [cn.hutool.json.JSONObject] to [xxx] #3649

Closed wanghuizuo closed 1 month ago

wanghuizuo commented 1 month ago

版本情况

JDK版本: openjdk_8_201 hutool版本: 5.8.29(请确保最新尝试是否还有问题)

问题描述(包括截图)

JSONUtil.toBean时,如果Bean没有任何字段,会报错 image

  1. 复现代码
@Test
  public void testEmptyBean() {
    JSONUtil.toBean("{}", EmptyBean.class);
  }

  @Data
  public static class EmptyBean {}
  1. 堆栈信息 cn.hutool.core.convert.ConvertException: Can not Converter from [cn.hutool.json.JSONObject] to [com.x.core.JsonTest$EmptyBean]

    at cn.hutool.core.convert.ConverterRegistry.convert(ConverterRegistry.java:247) at cn.hutool.core.convert.ConverterRegistry.convert(ConverterRegistry.java:262) at cn.hutool.core.convert.Convert.convertWithCheck(Convert.java:753) at cn.hutool.json.JSONConverter.jsonToBean(JSONConverter.java:138) at cn.hutool.json.JSONConverter.jsonConvert(JSONConverter.java:96) at cn.hutool.json.JSON.toBean(JSON.java:179) at cn.hutool.json.JSON.toBean(JSON.java:155) at cn.hutool.json.JSONUtil.toBean(JSONUtil.java:447) at cn.hutool.json.JSONUtil.toBean(JSONUtil.java:420)

  2. 测试涉及到的文件(注意脱密)

比如报错的Excel文件,有问题的图片等。

looly commented 1 month ago

你可以设置ignoreError为true跳过

image

wanghuizuo commented 1 month ago

我期望返回一个空的实例,设置ignoreError=true,返回的是null

looly commented 1 month ago

@wanghuizuo 因为没有字段也没有getter和setter,这个对象不被当作一个bean,所以注入失败。

此块逻辑暂无。

wanghuizuo commented 1 month ago

hutool旧版本没有这个问题,因此喜欢hutool的开发者把项目升级到最新版本可能会给他们带来未知的BUG,他可能需要把所有JSONUtil.toBean的调用检查一遍,这些影响可能非常重要,希望能酌情考虑

looly commented 1 month ago

@wanghuizuo 新版本的Hutool对Bean的判断更加严格,就是为了防止自定义对象被当作bean误判断。

5.8.30增加此逻辑:

image

对于空值转空对象,做了单独判断。

looly commented 1 month ago

关联:https://github.com/dromara/hutool/issues/2564