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系,两者互不影响. 搭配使用会有意想不到的结果哦.