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(){ ListuserList = 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); }}