fastJson使用

转载 https://www.cnblogs.com/wbxk/p/10064737.html

示例代码:

public class Person {

    // JSONField ———————— 这是一个注解,用于配置在JavaBean,可以配置在getter/setter方法或者字段上,也可以直接配置在属性上。

    @JSONField(ordinal = 4,name = "ID")
    private Integer id;

    @JSONField(ordinal = 3,serialize = false)
    private String name;

    @JSONField(ordinal = 2,deserialize = false)
    private Integer age;

    @JSONField(ordinal = 1,format = "yyyy-MM-dd")
    private Date createTime;

    //ordinal默认为0
    //指定序列化规则【规则见 https://www.cnblogs.com/wbxk/p/10064737.html 】,字段为null的时候依然参加序列化
    @JSONField(serialzeFeatures = SerializerFeature.WriteMapNullValue)
    private String phone;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", createTime=" + createTime +
                ", phone='" + phone + '\'' +
                '}';
    }


    /*测试代码*/
    public static void main(String[] args) {
        Person person = new Person();
        person.setAge(12345);
        person.setName("csc");
        person.setId(11);
//        person.setPhone("iphone");
        person.setCreateTime(new Date());

        String personStr = JSON.toJSONString(person);
        /*结果:按照指定字段顺序序列化的,id字段序列化为ID,name没有参加序列化,createtime按照指定格式序列化,phone为null,但是参与了序列化。
        * (FastJson默认的序列化规则是字段的值为null的时候,不参与序列化,serialzeFeatures=SerializerFeature.WriteMapNullValue可以在value的值为null的时候,依然会把它的值序列化出来。)*/
        System.out.println(personStr);


        Person newPerson = JSON.parseObject(personStr,Person.class);
        /*age没有参与反序列化*/
        System.out.println(newPerson.toString());

    }
}

输出

{“phone”:null,“createTime”:“2019-04-02”,“age”:12345,“ID”:11}
Person{id=11, name=‘null’, age=null, createTime=Tue Apr 02 00:00:00 CST 2019, phone=‘null’}

你可能感兴趣的:(fastJson)