net.sf.json、fastjson、objectMapper打印入参的区别

最近与外部系统对接,需要打印外部系统的提交参数,一开始用net.sf.json打印,遇到一些坑,总结如下:

1.net.sf.json:打印对象的所有字段,BigDecimal类型的值默认为0,即使不设置也是0(这个是坑,好几次我以为别人提交参数有误)

2.fastjson:只打印有值的字段

3.objectMapper:打印所有字段,没有设置的字段则为null

public class CargoInfo implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private String goodsType;
	
	private String KjNhOrderNo;
	
	public String getKjNhOrderNo() {
		return KjNhOrderNo;
	}

	public void setKjNhOrderNo(String kjNhOrderNo) {
		KjNhOrderNo = kjNhOrderNo;
	}

	private BigDecimal piece;
	
	private BigDecimal weight;

	public String getGoodsType() {
		return goodsType;
	}

	public void setGoodsType(String goodsType) {
		this.goodsType = goodsType;
	}

	public BigDecimal getPiece() {
		return piece;
	}

	public void setPiece(BigDecimal piece) {
		this.piece = piece;
	}

	public BigDecimal getWeight() {
		return weight;
	}

	public void setWeight(BigDecimal weight) {
		this.weight = weight;
	}

}
public class Main {

	public static void main(String[] args) throws JsonProcessingException {
		
		CargoInfo cargoInfo = new CargoInfo();
		cargoInfo.setGoodsType("test");
		
		//net.sf.json
		String string = JSONObject.fromObject(cargoInfo).toString();
		System.out.println("net.sf.json>>>>>>>>>>>" + string);
		
		//fastjson
		String fastJson = JSON.toJSONString(cargoInfo);
		System.out.println("fastjson>>>>>>>>" + fastJson);
		
		//objectMapper
		ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(cargoInfo);
        System.out.println("objectMapper>>>>>>>>>" + jsonString);
	}
	
}

打印结果:

net.sf.json>>>>>>>>>>>{"piece":0,"weight":0,"goodsType":"test","kjNhOrderNo":""}
fastjson>>>>>>>>{"goodsType":"test"}
objectMapper>>>>>>>>>{"goodsType":"test","piece":null,"weight":null,"kjNhOrderNo":null}

可以请我喝奶茶吗,哈哈

你可能感兴趣的:(net.sf.json、fastjson、objectMapper打印入参的区别)