欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  Java

FastJson常用的场景介绍(代码)

程序员文章站 2022-04-04 23:23:37
...

本篇文章给大家带来的内容是关于FastJson常用的场景介绍(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

JavaBean

package com.daily.json;

import com.alibaba.fastjson.annotation.JSONField;

import java.util.Date;

public class Student {

    @JSONField(name = "NAME", ordinal = 3)
    private String name;
    @JSONField(ordinal = 2)
    private int age;
    @JSONField(format = "yyyy-MM-dd HH:mm:ss", ordinal = 1)
    private Date birthDay;
    @JSONField(serialize = false)
    private String addr;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Date getBirthDay() {
        return birthDay;
    }

    public void setBirthDay(Date birthDay) {
        this.birthDay = birthDay;
    }

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }
}

测试类

package com.daily.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.PropertyFilter;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class TestFastJson {

    private static Student student;
    private static List<Student> studentList;
    static {
        student = new Student();
        student.setName("张三");
        student.setAge(18);
        student.setBirthDay(new Date());
        student.setAddr("湖南");

        studentList = new ArrayList<>();
        studentList.add(student);
        studentList.add(student);
    }

    private static PropertyFilter propertyFilter = (object, name, value) -> {
        if (name.equals("age") && value.equals(18)) {
                return false;
        }
        return true;
    };

    public static void main(String[] args) {
        String studentStr = JSON.toJSONString(student);
        //转对象
        Student student1 = JSON.parseObject(studentStr, Student.class);
        Student student2 = JSON.parseObject(studentStr, new TypeReference<Student>() {});
        //转集合
        String studentListStr = JSON.toJSONString(studentList);
        List<Student> students = JSON.parseArray(studentListStr, Student.class);
        List<Student> students2 = JSON.parseObject(studentListStr, new TypeReference<List<Student>>() {
        });
        //过滤字段,默认过滤null
        String student3 = JSON.toJSONString(student, propertyFilter);
        System.out.println(student3);
    }
}

以上就是FastJson常用的场景介绍(代码)的详细内容,更多请关注其它相关文章!

相关标签: java