bean轉json時null欄位不轉換的方法
阿新 • • 發佈:2019-01-04
1.使用GSON時,預設不對null欄位進行轉換,而ObjectMapper和JSONObject預設對null欄位進行轉換
(1)使用GSON時,對null欄位進行轉換的設定
Gson gsonSerializeNull = new GsonBuilder().serializeNulls().create();
(2)使用ObjectMapper對null欄位不進行轉換的設定
ObjectMapper objectMapper= new ObjectMapper();
objectMapper.setSerializationInclusion(Include.NON_NULL);
(3)使用json-lib的JSONObject在bean轉json時對null欄位不轉換的設定
PropertyFilter filter = new PropertyFilter() { public boolean apply(Object object, String fieldName, Object fieldValue) { return null == fieldValue; } }; jsonConfig.setJsonPropertyFilter(filter); System.out.println(JSONObject.fromObject(s, jsonConfig).toString());
2.測試
Student類
package com.beanjson.test; public class Student { private String name; private int id; private Integer age = null; public Student() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
main函式
package com.beanjson.test; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; import net.sf.json.util.PropertyFilter; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class Test { private static ObjectMapper objectMapper; public static void main(String[] args) throws JsonProcessingException { Student s = new Student(); s.setName("abc"); s.setId(1); s.setAge(null); System.out.println("----------gson(預設對null不轉換)---------"); Gson gson = new Gson(); System.out.println(gson.toJson(s)); System.out.println("----------gson(對null欄位轉換)---------"); Gson gsonSerializeNull = new GsonBuilder().serializeNulls().create(); System.out.println(gsonSerializeNull.toJson(s)); System.out.println("----------objectMapper對null欄位不轉換的設定---------"); objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(Include.NON_NULL); System.out.println(objectMapper.writeValueAsString(s)); System.out.println("----------json-lib對null欄位不轉換的設定---------"); JsonConfig jsonConfig = new JsonConfig(); PropertyFilter filter = new PropertyFilter() { public boolean apply(Object object, String fieldName, Object fieldValue) { return null == fieldValue; } }; jsonConfig.setJsonPropertyFilter(filter); System.out.println(JSONObject.fromObject(s, jsonConfig).toString()); } }