物件轉Json字串時,忽略指定屬性
阿新 • • 發佈:2019-01-05
1、FastJson轉Json字串時,忽略指定屬性
1.1使用註解@JSONField
以下Beanpackage com.gomefinance.esign; import com.alibaba.fastjson.annotation.JSONField; import lombok.Getter; import lombok.Setter; import java.io.Serializable; /** * 本地簽署資訊 * Created by JHAO on 2017/5/31. */ @Setter @Getter public class FastJsonInputBean implements Serializable { // 合同模板ID private String contractTemplateId; // 合同號 private String contractId; // Base64編碼的合同 @JSONField(serialize = false) private String contractImage; private String contractVersion; }
FastJsonInputBean inputBean = new FastJsonInputBean(); inputBean.setContractImage("contractImage"); inputBean.setContractTemplateId("templateId"); inputBean.setContractId("comtractId"); inputBean.setContractVersion("contractVersion"); System.out.println("JSONField(serialize = false)忽略contractImage屬性:"+JSON.toJSONString(inputBean));
列印結果:{"contractId":"comtractId","contractTemplateId":"templateId","contractVersion":"contractVersion"}
1.2Filter指定序列化的欄位
SimplePropertyPreFilter filter = new SimplePropertyPreFilter(FastJsonInputBean.class, "contractTemplateId"); System.out.println("filter忽略contractTemplateId屬性:"+JSONObject.toJSONString(inputBean, filter));
列印結果:{"contractTemplateId":"templateId"}
2、JackSon忽略欄位
@JsonIgnoreProperties主鍵或者在欄位上使用@JsonIgnore
package com.gomefinance.esign;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
/**
* 本地簽署資訊
* Created by JHAO on 2017/5/31.
*/
@Setter
@Getter
@JsonIgnoreProperties({"contractTemplateId", "contractImage"})
public class JackSonInputBean implements Serializable {
// 合同模板ID
private String contractTemplateId;
// 合同號
@JsonIgnore
private String contractId;
// Base64編碼的合同
private String contractImage;
private String contractVersion;
}
JackSonInputBean jackSonInputBean = new JackSonInputBean();
jackSonInputBean.setContractImage("contractImage");
jackSonInputBean.setContractTemplateId("templateId");
jackSonInputBean.setContractId("comtractId");
jackSonInputBean.setContractVersion("contractVersion");
ObjectMapper objectMapper = new ObjectMapper();
System.out.println("JackSon JsonIgnore忽略contractId屬性:"+objectMapper.writeValueAsString(jackSonInputBean));
列印結果:{"contractVersion":"contractVersion"}