fastjson2 icon indicating copy to clipboard operation
fastjson2 copied to clipboard

[BUG] JSONArray.toJavaList()不支持Boolean类型到boolean类型的转换,导致赋值错误

Open Bsheepcoder opened this issue 1 year ago • 2 comments

问题描述

JSONArray.toJavaList()不支持Boolean类型到boolean类型的转换,导致赋值错误

环境信息

请填写以下信息:

  • OS信息: windows 11
  • JDK信息: jdk 1.8
  • 版本信息:fastjson2-2.0.23.jar

重现步骤

string中为true,解析后为false

public class IegnrstOpusJsonTest {

    public static class JSONBooleanTest {
        @JsonField("is_cooperate")
        private boolean cooperate;
    }

    @Test
    public void toJsonList() throws IOException {
        List<JSONBooleanTest> opusResults = null;
        String string = "[{\"is_cooperate\":true}]";
        opusResults = JSONArray.parseArray(string).toJavaList(JSONBooleanTest.class);
        System.out.println(opusResults.toString());
    }
}

image

期待的正确结果

应该解析为true

Bsheepcoder avatar Sep 06 '24 07:09 Bsheepcoder

两种解决方案:1. JSONBooleanTest添加get与set方法;2. toJavaList指定JSONReader.Feature.FieldBased

yanxutao89 avatar Sep 06 '24 14:09 yanxutao89

这不是 bug,而是你自己用法不对

  1. 你的字段是 private 的,且不提供 getset 方法,当然不能反序列化。
  2. 你使用的注解 @JsonField("is_cooperate") 根本就不是 Fastjson 的注解,Fastjson2 的注解是这样的
// 这才是 Fastjson2 的注解 !
@com.alibaba.fastjson2.annotation.JSONField(name = "is_cooperate")

你把注解修改正确,解决办法如下(选其一即可):

  1. 添加该字段的 get、set 方法
  2. private 改为 public
  3. 使用重载方法,指定 JSONReader.Feature.FieldBased 属性,也就是: JSONArray.parseArray(string).toList(JSONBooleanTest.class, JSONReader.Feature.FieldBased)

CodePlayer avatar Sep 18 '24 13:09 CodePlayer