参考代码:https://github.com/huiyiwu/spring-boot-simple/spring-boot-mvc
1. 概念
- 序列化:把Java对象转为字节序列的过程
- 反序列化:把字节序列恢复为Java对象的过程
2. 对象序列化作用
- 把对象的字节序列永久地保存在硬盘上,通常存放在一个文件中;(持久化对象)
- 在网络上传送对象的字节序列。(网络传输对象)
3. 自定义JsonSerializer类
import java.io.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import org.springframework.boot.jackson.*;
@JsonComponent
public class ClothColorJsonSerializer {
public static class ClothColorSerializer extends JsonSerializer<ClothColorPojo> {
@Override
public void serialize(ClothColorPojo clothColorPojo, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// 对象转为字节流
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("color",getColor(clothColorPojo.getColor()));
jsonGenerator.writeEndObject();
}
public String getColor(Color color) {
int r = (int) Math.round(color.getRed()*255.0);
int g = (int) Math.round(color.getRed()*255.0);
int b = (int) Math.round(color.getBlue()*255.0);
return String.format("#%02x%02x%02x",r,g,b);
}
}
public static class ClothColorDeserializer extends JsonDeserializer<ClothColorPojo>{
@Override
public ClothColorPojo deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
// 字节流转为对象
TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
TextNode colorNode = (TextNode) treeNode.get("color");
return new ClothColorPojo(Color.web(colorNode.asText()));
}
}
}
4. 测试:
@RequestMapping("serializer")
public Map<String,Object> jsonSerializer(){
Map<String,Object> result = new HashMap<>();
ClothColorPojo clothColorPojo = new ClothColorPojo(Color.ANTIQUEWHITE);
String colorJson = "{\"color\":\"#f0f8ff\"}";
ObjectMapper objectMapper = new ObjectMapper();
try {
result.put("serializer",objectMapper.writeValueAsString(clothColorPojo));
// result.put("deserilizer",objectMapper.readValue(colorJson,ClothColorPojo.class));
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
测试结果: