温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

FastJson常用的场景有哪些

发布时间:2020-10-28 14:26:07 来源:亿速云 阅读:181 作者:小新 栏目:编程语言

这篇文章主要介绍了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常用的场景有哪些内容对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,遇到问题就找亿速云,详细的解决方法等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI