json字符串忽略null,忽略字段,首字母大写等gson,jackson,fastJson实现demo
代码语言:javascript复制package com.example.core.mydemo.json.vo;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
@JsonAutoDetect(fieldVisibility= JsonAutoDetect.Visibility.ANY, getterVisibility=JsonAutoDetect.Visibility.NONE)
public class JsonReqVo {
@Expose
@SerializedName("Username") //gson
@JSONField(name= "Username") //fastjson
private String username;
@Expose
@JsonProperty("Status")
private String status; //jackson
@Expose
private String school;
@Expose
private String password;
@Expose
private String address;
@JsonIgnore //可以直接放在field上面表示要忽略的filed //jackson
@Expose(serialize = false) //gson
@JSONField(serialize = false) //fastjson
private String apikey;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getApikey() {
return apikey;
}
public void setApikey(String apikey) {
this.apikey = apikey;
}
}
package com.example.core.mydemo.json;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
public class JsonUtils {
// 定义jackson对象
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
* 将对象转换成json字符串。
* <p>Title: pojoToJson</p>
* <p>Description: </p>
* @param data
* @return
*/
public static String objectToJson(Object data) {
try {
MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
//通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化 Include.NON_NULL 属性为NULL 不序列化
//Include.Include.ALWAYS 默认
//Include.NON_DEFAULT 属性为默认值不序列化
//Include.NON_EMPTY 属性为 空(“”) 或者为 NULL 都不序列化
//Include.NON_NULL 属性为NULL 不序列化
String string = MAPPER.writeValueAsString(data);
return string;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
/**
* 将json结果集转化为对象
*
* @param jsonData json数据
* @param beanType 对象中的object类型
* @return
*/
public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
try {
MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
T t = MAPPER.readValue(jsonData, beanType);
return t;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将json数据转换成pojo对象list
* <p>Title: jsonToList</p>
* <p>Description: </p>
* @param jsonData
* @param beanType
* @return
*/
public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) {
MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
try {
List<T> list = MAPPER.readValue(jsonData, javaType);
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
package com.example.core.mydemo.json;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.PascalNameFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.example.core.mydemo.json.vo.JsonReqVo;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
/**
* last print:
* gson={"Username":"刘天王","status":"1","password":"","apikey":"1111111111111"}
* gson2={"Username":"刘天王","status":"1","school":null,"password":"","address":null,"apikey":"1111111111111"}
* gson3={"Username":"刘天王","status":"1","password":""}
* json={"username":"刘天王","password":"","Status":"1"}
* json2={"Username":"刘天王","password":"","status":"1"}
* jsonStr3={"Username":"刘天王","Password":"","Status":"1"}
* jsonStr4={"Username":"刘天王","password":"","status":"1"}
* jsonStr5={"Username":"刘天王","address":null,"password":"","school":null,"status":"1"}
* jsonStr6={"Username":"刘天王","password":"","status":"1"}
* jsonStr7={"Username":"刘天王","password":"","status":"1"}
* jsonStr8={"Username":"刘天王","address":"","password":"","school":"","status":"1"}
* jsonStr9={"Username":"刘天王","password":"","status":"1"}
*
*/
//@RunWith(SpringRunner.class)
//@SpringBootTest()
public class JsonUtilsTest {
@Test
public void test(){
JsonReqVo reqVo = new JsonReqVo();
reqVo.setApikey("1111111111111");
reqVo.setStatus("1");
reqVo.setUsername("刘天王");
reqVo.setPassword("");
reqVo.setSchool(null);
//Gson
String g1 = new Gson().toJson(reqVo);
//首字母大写 @SerializedName("Username")
//gson默认忽略null
//gson={"Username":"刘天王","status":"1","password":"","apikey":"1111111111111"}
System.out.println("gson=" g1);
// Both Gson instances must have serializeNulls()
final Gson gson = new GsonBuilder().serializeNulls().create();
//gson2={"Username":"刘天王","status":"1","school":null,"password":"","address":null,"apikey":"1111111111111"}
System.out.println("gson2=" gson.toJson(reqVo));
GsonBuilder builder = new GsonBuilder();
builder.excludeFieldsWithoutExposeAnnotation();
Gson gson3 = builder.create();
//@Expose(serialize = false) 其他的字段也需要加上
//gson3={"Username":"刘天王","status":"1","password":""}
System.out.println("gson3=" gson3.toJson(reqVo));
// jackson
String json = JsonUtils.objectToJson(reqVo);
//通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化 Include.NON_NULL 属性为NULL 不序列化
//加上 @JsonAutoDetect(fieldVisibility= JsonAutoDetect.Visibility.ANY, getterVisibility=JsonAutoDetect.Visibility.NONE)
/**
* JsonAutoDetect.Visibility.ANY : 表示所有字段都可以被发现, 包括private修饰的字段, 解决大小写问题
* JsonAutoDetect.Visibility.NONE : 表示get方法不可见,解决字段重复问题
*/
//需要将字段设置为首字母大写
//json={"username":"刘天王","password":"","Status":"1"}
System.out.println("json=" json);
// fastJson
//@JSONField(name= "SjAreasNum") 单个字段 默认过滤空值
String ss = JSON.toJSONString(reqVo);
//json2={"Username":"刘天王","apikey":"1111111111111","password":"","status":"1"}
System.out.println("json2=" ss);
//全部的首字母大写 null忽略,空字符串保留
String jsonStr3= JSON.toJSONString(reqVo ,new PascalNameFilter());
//jsonStr3={"Username":"刘天王","Apikey":"1111111111111","Password":"","Status":"1"}
System.out.println("jsonStr3=" jsonStr3);
//QuoteFieldNames:输出key时是否使用双引号,默认为true
String jsonStr4= JSONObject.toJSONString(reqVo, SerializerFeature.QuoteFieldNames);
//jsonStr4={"Username":"刘天王","apikey":"1111111111111","password":"","status":"1"}
System.out.println("jsonStr4=" jsonStr4);
//WriteMapNullValue:是否输出值为null的字段,默认为false
String jsonStr5= JSONObject.toJSONString(reqVo, SerializerFeature.WriteMapNullValue);
//有效
//jsonStr5={"Username":"刘天王","address":null,"apikey":"1111111111111","password":"","school":null,"status":"1"}
System.out.println("jsonStr5=" jsonStr5);
//WriteNullNumberAsZero:数值字段如果为null,输出为0,而非null
String jsonStr6= JSONObject.toJSONString(reqVo, SerializerFeature.WriteNullNumberAsZero);
//jsonStr6={"Username":"刘天王","apikey":"1111111111111","password":"","status":"1"}
System.out.println("jsonStr6=" jsonStr6);
//WriteNullListAsEmpty:List字段如果为null,输出为[],而非null
String jsonStr7= JSONObject.toJSONString(reqVo, SerializerFeature.WriteNullListAsEmpty);
//jsonStr7={"Username":"刘天王","apikey":"1111111111111","password":"","status":"1"}
System.out.println("jsonStr7=" jsonStr7);
//WriteNullStringAsEmpty:字符类型字段如果为null,输出为”“,而非null
String jsonStr8= JSONObject.toJSONString(reqVo, SerializerFeature.WriteNullStringAsEmpty);
//有效
//jsonStr8={"Username":"刘天王","address":"","apikey":"1111111111111","password":"","school":"","status":"1"}
System.out.println("jsonStr8=" jsonStr8);
//WriteNullBooleanAsFalse:Boolean字段如果为null,输出为false,而非null
String jsonStr9= JSONObject.toJSONString(reqVo, SerializerFeature.WriteNullBooleanAsFalse);
//jsonStr9={"Username":"刘天王","apikey":"1111111111111","password":"","status":"1"}
System.out.println("jsonStr9=" jsonStr9);
}
}