java json 多余属性_java 对象转json忽略某个属性

1、FastJson转Json字符串时,忽略指定属性

1.1使用注解@JSONField

以下Bean

package 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"}

原文:https://blog.csdn.net/a491857321/article/details/78761857

你可能感兴趣的:(java,json,多余属性)