定制序列化之@JSONType的使用

package com.ant.jdk8.json;

import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.annotation.JSONType;

import java.util.Date;

@JSONType(includes = {"name","hireDate"},ignores = {"age"})
public class User {

    private String name;

    private int age;

    @JSONField(format="yyyy-MM-dd HH:mm:ss")
    private Date hireDate;

    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 getHireDate() {
        return hireDate;
    }

    public void setHireDate(Date hireDate) {
        this.hireDate = hireDate;
    }

    public User(String name, int age, Date hireDate) {
        this.name = name;
        this.age = age;
        this.hireDate = hireDate;
    }

    public User() {
    }
}
package com.ant.jdk8.json;

import com.alibaba.fastjson.JSON;

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

public class JsonDemo {

    public static void main(String[] args) {
        convertCollectionToJson();
    }

    public static void convertCollectionToJson(){
        List<User> userList = new ArrayList<>();
        userList.add(new User("tom",20,new Date()));
        userList.add(new User("jack",25,new Date()));
        String jsonString = JSON.toJSONString(userList,true);//true表示转换为带格式的json文本
        System.out.println(jsonString);
    }

}

posted on 2018-06-24 19:35  shammgod_code  阅读(1702)  评论(0编辑  收藏  举报

导航