大佬教程收集整理的这篇文章主要介绍了使用fastjson,gson解析null值的时候键保留,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
由于业务需求。。。所以查阅资料,总结如下:
使用gson实现方法:只需要把new Gson()改为:
new GsonBuilder().serializeNulls().create(); 就可以了
public class Test { public static void main(String[] args) { Gson gson= new GsonBuilder().serializeNulls().create(); Map < String,Object > jsonMap = new HashMap< String,Object>(); jsonMap.put("a",1); jsonMap.put("b",""); jsonMap.put("c",null); jsonMap.put("d","wuzhuti.cn"); String str = gson.toJson(jsonMap); System.out.println(str); person peson1 = new person(); peson1.setAge(1); peson1.setName(null); System.out.println(gson.toJson(peson1)); } } class person{ private int age; private String name; public int getAge() { return age; } public void setAge(int agE) { this.age = age; } public String getName() { return name; } public void setName(String Name) { this.name = name; } }
使用fastjson实现方法:只需要再toJsonString的时候加上
serializerFeature.WriteMapNullValue 这个参数。
public class FastJsonTest { public static void main(String[] args) { /* * QuoteFieldNames———-输出key时是否使用双引号,默认为true * WriteMapNullValue——–是否输出值为null的字段,默认为false * WriteNullnumberAsZero—-数值字段@R_874_5330@,输出为0,而非null * WriteNullListAsEmpty—–List字段@R_874_5330@,输出为[],而非null * WriteNullStringAsEmpty—字符类型字段@R_874_5330@,输出为"",而非null * WriteNullBooleanAsfalse–Boolean字段@R_874_5330@,输出为false,而非null */ Map<String,Object> jsonMap = new HashMap<String,Object>(); jsonMap.put("a",1); jsonMap.put("b",""); jsonMap.put("c",null); jsonMap.put("d","json"); String str = JSONObject.toJSONString(jsonMap); // 忽略null输出 System.out.println(str); String str2 = JSONObject.toJSONString(jsonMap,serializerFeature.WriteMapNullvalue); System.out.println(str2); String json = "{\"fail\":null,\"updatetimestamp\":\"1484096131863\",\"productName\":\"json测试\"}"; // 忽略null输出 System.out.println(JSON.parse(json)); // System.out.println(JSONObject.toJSON(json)); } }
以上。
以上是大佬教程为你收集整理的使用fastjson,gson解析null值的时候键保留全部内容,希望文章能够帮你解决使用fastjson,gson解析null值的时候键保留所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。