1.实体类
package jsonArrayjsonObject.cn; import java.io.Serializable; import java.util.Date; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.serializer.SerializerFeature; public class User implements Serializable{ private static final long serialVersionUID = 1L; // 配置序列化和反序列化的顺序,1.2.42以上版本支持。默认是以fieldName的字母序进行序列化的 @JSONField(ordinal = 0) private Long id; @JSONField(ordinal = 1, name = "na") private String name; // 序列化与反序列化,默认均为true @JSONField(ordinal = 2, serialize = false, deserialize = false) private Integer age; // 默认序列化规则是当字段值为null时,是不序列化该字段的。当设置规则后,value为null时,依然会把它的值序列化出来 @JSONField(ordinal = 3, serialzeFeatures = SerializerFeature.WriteMapNullValue) private String address; // 指定时间格式 @JSONField(ordinal = 4, format = "yyyy-MM-dd HH:mm:ss") private Date birthDate; public Long getId() { return id; } public void setId(Long 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 String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } }
2.测试类
package jsonArrayjsonObject.cn; import java.util.Date; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SimplePropertyPreFilter; public class Test { public static void main(String[] args) { test1(); } // 测试SimplePropertyPreFilter 和 JsonField 注解 static void test1(){ User user = new User(); user.setId(1L); user.setAge(12); user.setName("zhangsan"); user.setBirthDate(new Date()); SimplePropertyPreFilter filter = new SimplePropertyPreFilter(User.class, "na", "address"); String jsonString1 = JSON.toJSONString(user); String jsonString2 = JSON.toJSONString(user, filter); System.out.println(jsonString1); System.out.println(jsonString2); } }
3.结果
{"id":1,"na":"zhangsan","address":null,"birthDate":"2018-01-08 14:24:28"} {"na":"zhangsan","address":null}
4.参考
关于@JsonField的name属性详解见:http://www.cnblogs.com/softidea/p/5681928.html
原文地址:https://www.cnblogs.com/toSeeMyDream/p/9785869.html
时间: 2024-10-21 13:34:03