关于json解析那些事,Gson和JSON

 com.alibaba.fastjson.JSON;

@Data
@ToString
public class ZbEnterpriseDto {

	/**
	 * 企业ID
	 */
	private int entId;

	public static void main(String[]args){
		String json = "{\"ent_id\":12}";
        String json1 = "{\"entid\":12}";
	    ZbEnterpriseDto zbEnterpriseDto = JSON.parseObject(json, ZbEnterpriseDto.class);
	}
}

对于阿里的fastjson,无论是json或是json1都可以正确的解析. 但是如果使用Gson则无法正确的解析

com.google.gson.Gson
@Data
@ToString
public class ZbEnterpriseDto {

	/**
	 * 企业ID
	 */
	@JSONField(name = "ent_id")
	private int entId;

	public static void main(String[]args){
		String json = "{\"ent_id\":12}";
		Gson gson = new Gson();
		//ZbEnterpriseDto zbEnterpriseDto = gson.fromJson(json, ZbEnterpriseDto.class);
		ZbEnterpriseDto zbEnterpriseDto = JSON.parseObject(json, ZbEnterpriseDto.class);
		//Gson gson = new Gson();

		//System.out.println(gson.toJson(zbEnterpriseDto));
		System.out.println(gson.toJson(zbEnterpriseDto)); //输出字段名entId
        System.out.println(JSON.toJson(zbEnterpriseDto)); //输出字段名ent_id

	}
}

使用gson将对象转换为json字符串时不受@JSONField影响,@JSONField只会对JSON.toJson()产生影响.

总结:

@JSONField和JSON.toJson()都是阿里系, gson时Google系,两者互不影响. 搭配使用会有意想不到的结果哦.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值