关于FastJSON序列化Bean时对get方法调用的细节

结论

使用JSON.toJSONString去序列化Bean的时候
FastJSON会把Bean里面的get开头有返回值没有参数的方法都调用一遍。

看代码

package org.example.domain;

import lombok.Getter;
import lombok.Setter;

/**
 * @program: parent_pro
 * @description:
 * @author: 渭水
 * @create: 2023/10/31
 */
@Getter
@Setter
public class OtherPerson {
    private Integer age;
    public String getPerson2(String s) {
        System.out.println("getPerson");
        return "abc";
    }

    public void getPerson4() {
        System.out.println("getPerson4");
    }

    public void getPerson5(String s) {
        System.out.println("getPerson5");
    }

    public String getPerson3() {
        System.out.println("getPerson3");
        return "abc";
    }
}

测试类如下

package org.example;

import com.alibaba.fastjson2.JSON;

import org.example.domain.OtherPerson;

/**
 * @program: parent_pro
 * @description:
 * @author: 渭水
 * @create: 2023/11/03
 */
public class JSONTest {
    public static void main(String[] args) {
        OtherPerson otherPerson = new OtherPerson();
        otherPerson.setAge(18);
        System.out.println(JSON.toJSONString(otherPerson));
    }
}

运行结果
关于FastJSON序列化Bean时对get方法调用的细节_第1张图片

关于ArrayIndexOutOfBoundsException

另外这里用的FastJSON版本是

    <dependency>
      <groupId>com.alibaba.fastjson2</groupId>
      <artifactId>fastjson2</artifactId>
      <version>2.0.41</version>
    </dependency>

如果版本低于2.0.35,且bean里面有返回值为void的且get开头的方法就会报错:java.lang.ArrayIndexOutOfBoundsException

你可能感兴趣的:(java,开发语言)