简介
Jackson是Spring默认使用的JSON序列化/反序列化工具。
使用方式
创建ObjectMapper对象
ObjectMapper mapper = new ObjectMapper();
mapper
//.setVisibility(PropertyAccessor.ALL, Visibility.NONE)
//.setVisibility(PropertyAccessor.FIELD, Visibility.ANY)
.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
Object转JSON
public static String toJson(Object obj) {
try {
return mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
logger.error("to json error.", e);
}
return null;
}
JSON转Object
// 简单类型:Xxx xxx = toObject("<json>", Xxx.class)
public static <T> T toObject(String content, Class<T> valueType) {
try {
return mapper.readValue(content, valueType);
} catch (JsonProcessingException e) {
logger.error("to object error.", e);
}
return null;
}
// 带泛型的类型:List<Xxx> xxxList = toObject("<json>", new TypeReference<List<Xxx>>(){});
public static <T> T toObject(String content, TypeReference<T> valueTypeRef) {
try {
return mapper.readValue(content, valueTypeRef);
} catch (JsonProcessingException e) {
logger.error("to object error.", e);
}
return null;
}
以JsonNode的方式读取Json
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonString);
System.out.println(jsonNode.get("name").asText()); // 输出:John
System.out.println(jsonNode.get("age").asInt()); // 输出:30
System.out.println(jsonNode.get("city").asText()); // 输出:New York
忽略某个字段
public class User {
private String username;
@JsonIgnore // 忽略序列化
private String password;
}
序列化忽略某个字段,反序列化不忽略
public class User {
private String username;
// 如果只需要在反序列化的时候忽略,则使用READ_ONLY
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
}
增加全局类型转换器
// 序列化逻辑
public class CustomDateSerializer extends JsonSerializer<Date> {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
@Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
String formattedDate = dateFormat.format(date);
jsonGenerator.writeString(formattedDate);
}
}
// 反序列化逻辑
public class CustomDateDeserializer extends JsonDeserializer<Date> {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
@Override
public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
String dateString = jsonParser.getText();
try {
return dateFormat.parse(dateString);
} catch (ParseException e) {
throw new IOException("Error parsing date: " + dateString, e);
}
}
}
// 配置到ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(Date.class, new CustomDateSerializer());
module.addDeserializer(Date.class, new CustomDateDeserializer());
objectMapper.registerModule(module);
// 测试
Date date = new Date();
String json = objectMapper.writeValueAsString(date);
System.out.println(json); // 输出: "2022-01-01"
Date deserializedDate = objectMapper.readValue("\"2022-01-01\"", Date.class);
System.out.println(deserializedDate); // 输出:Sat Jan 01 00:00:00 GMT 2022
为某个属性设置序列化类
// 自定义序列化类
public class CustomSerializer extends JsonSerializer<String> {
@Override
public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// 自定义序列化逻辑
String serializedValue = "*****";
jsonGenerator.writeString(serializedValue);
}
}
// 在需要的属性上设置使用自定义序列化类
public class User {
private String username;
// 如果只需要在反序列化的时候忽略,则使用READ_ONLY
@JsonSerialize(using = CustomSerializer.class)
private String password;
}
// 测试
User user = new User("Zhangsan", "123456");
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(myObject);
System.out.println(json); // 输出:{"username":"Zhangsan", "password":"*****"}