当前位置: 首页 > 教程 > Fastjson >

Fastjson @JSONType

精华
小牛编辑
112浏览
2023-03-14

@JSONType注解和@JSONField注解的作用类似,但@JSONType是配置在类上,而不是字段或者getter/setter方法上。下面的示例,使用@JSONType注解来定制指定属性不序列化。

1 @JSONType注解的示例

1.1 编写Student类

package cn.xnip.domain;

import com.alibaba.fastjson.annotation.JSONType;

import java.util.Date;

/**
 * 小牛知识库网 - https://www.xnip.cn
 */
//不序列化studentAge和studentGender属性
@JSONType(ignores = {"studentAge","studentGender"})
public class Student {
    private String studentName;
    private Integer studentAge;
    private String studentGender;

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public Integer getStudentAge() {
        return studentAge;
    }

    public void setStudentAge(Integer studentAge) {
        this.studentAge = studentAge;
    }

    public String getStudentGender() {
        return studentGender;
    }

    public void setStudentGender(String studentGender) {
        this.studentGender = studentGender;
    }

    @Override
    public String toString() {
        return "Student{" +
                "studentName='" + studentName + '\'' +
                ", studentAge='" + studentAge + '\'' +
                ", studentGender='" + studentGender + '\'' +
                '}';
    }
}

1.2 编写测试类

package cn.xnip.fastjson;

import com.alibaba.fastjson.JSON;
import cn.xnip.domain.Student;

/**
 * 小牛知识库网 - https://www.xnip.cn
 */
public class MainApp {

    public static void main(String args[]){
        Student student = new Student();
        student.setStudentName("eric");
        student.setStudentGender("男");
        student.setStudentAge(20);

        String jsonstring = JSON.toJSONString(student);
        System.out.println(jsonstring);
    }

}

1.3 运行结果

{"studentName":"eric"}