1.實體類html
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.測試類java
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.結果json
{"id":1,"na":"zhangsan","address":null,"birthDate":"2018-01-08 14:24:28"} {"na":"zhangsan","address":null}
4.參考ide
關於@JsonField的name屬性詳解見:http://www.cnblogs.com/softidea/p/5681928.html測試