#暑期創作大賽#
當一個對象裡有些屬性值為null 的不想參與json序列化時,比如列印日志等場景進行序列化,null字段會占用日志長度。 可以采用如下兩種方式:
方法一:JsonInclude.Include.NON_NULL 注解
在類上面增加 @JsonInclude(JsonInclude.Include.NON_NULL)
示例:
//這個是類注解,表示該類執行個體化的對象裡,值為null的字段不參與序列化
@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
public class Person {
private Long id;
private String name;
}
public static void main(String[] args) {
Person p1 = new Person();
p1.setId(1L);
p1.setName("test1");
System.out.println("p1: " +JSONObject.toJSON(p1));
Person p2 = new Person();
p2.setId(1L);
System.out.println("p2: " +JSONObject.toJSON(p2));
}
輸出:
p1: {"name":"test1","id":1}
p2: {"id":1}
方法2:自定義一個ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
自定義一個JsonUtils工具類:
可以解析字元串,array, map等
@Slf4j
public class JsonUtils {
private static final String EMPTY_JSON = "{}";
private static final String EMPTY_ARRAY_JSON = "[]";
private static final ObjectMapper MAPPER = new ObjectMapper();
static {
MAPPER.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
}
public static String toJSON(@Nullable Object obj) {
if (obj == null) {
return null;
}
try {
return MAPPER.writeValueAsString(obj);
} catch (JsonProcessingException e) {
log.error("toJson error, ", e);
throw new BusinessException(e.getMessage());
}
}
public static <T> T parseObject(@Nullable String json, Class<T> valueType) {
if (json == null) {
return null;
}
try {
return MAPPER.readValue(json, valueType);
} catch (IOException e) {
log.error("parse object error, ", e);
throw new BusinessException(e.getMessage());
}
}
public static <E, T extends Collection<E>> T parseArray(String json,
Class<? extends Collection> collectionType, Class<E> valueType) {
if (StringUtils.isEmpty(json)) {
json = EMPTY_ARRAY_JSON;
}
try {
return MAPPER.readValue(json,
defaultInstance().constructCollectionType(collectionType, valueType));
} catch (IOException e) {
log.error("parseArray error, ", e);
throw new BusinessException(e.getMessage());
}
}
public static <T> List<T> parseArray(String json, Class<T> valueType) {
return parseArray(json, List.class, valueType);
}
/**
*
*/
public static <K, V, T extends Map<K, V>> T parseMap(String json, Class<? extends Map> mapType,
Class<K> keyType, Class<V> valueType) {
if (StringUtils.isEmpty(json)) {
json = EMPTY_JSON;
}
try {
return MAPPER.readValue(json,
defaultInstance().constructMapType(mapType, keyType, valueType));
} catch (IOException e) {
log.error("parseMap error, ", e);
throw new BusinessException(e.getMessage());
}
}
public static Map<String, Object> parseMap(String string) {
return parseMap(string, Map.class, String.class, Object.class);
}
}
測試
public static void main(String[] args) {
Person p1 = new Person();
p1.setId(1L);
p1.setName("test1");
System.out.println("p1: " +JsonUtils.toJSON(p1));
Person p2 = new Person();
p2.setId(1L);
System.out.println("p2: " +JsonUtils.toJSON(p2));
}
//輸出:
// p1: {"id":1,"name":"test1"}
// p2: {"id":1}