SpringBoot-底层是如何将对象转换JSON进行响应的
SpringBoot-底层是如何将对象转换JSON进行响应的
1.需求说明 : 演示返回 JSON 格式数据
2.应用实例
- SpringBoot 支持返回 JSON 格式数据,在启用 WEB 开发场景时,已经引入了相关依赖
2.创建src\main\java\com\llp\springboot\controller\ResponseController.java
@RestController
public class ResponseController {
//返回Monster数据-要求以json格式返回
@GetMapping("/get/monster")
public Monster getmonster(){
//开发中, monster对象是从DB获取-这里模拟一个monster对象
Monster monster = new Monster();
monster.setId(100);
monster.setName("奔波霸");
monster.setAge(200);
monster.setIsMarried(false);
monster.setBirth(new Date());
Car car = new Car();
car.setName("奔驰");
car.setPrice(222.2);
monster.setCar(car);
return monster;
}
}
3.测试
- Debug 一下 monster 对象以 Json 格式返回
AbstractJackson2HttpMessageConverter.java
@Override
protected void writeInternal(Object object, @Nullable Type type, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
//获取要转换的类型:application/json、application/xml
MediaType contentType = outputMessage.getHeaders().getContentType();
//默认是UTF-8
JsonEncoding encoding = getJsonEncoding(contentType);
Class<?> clazz = (object instanceof MappingJacksonValue ?
((MappingJacksonValue) object).getValue().getClass() : object.getClass());
ObjectMapper objectMapper = selectObjectMapper(clazz, contentType);
Assert.state(objectMapper != null, "No ObjectMapper for " + clazz.getName());
OutputStream outputStream = StreamUtils.nonClosing(outputMessage.getBody());
//获取要转的generator对象
try (JsonGenerator generator = objectMapper.getFactory().createGenerator(outputStream, encoding)) {
writePrefix(generator, object);
Object value = object;
Class<?> serializationView = null;
FilterProvider filters = null;
JavaType javaType = null;
if (object instanceof MappingJacksonValue) {
MappingJacksonValue container = (MappingJacksonValue) object;
value = container.getValue();
serializationView = container.getSerializationView();
filters = container.getFilters();
}
if (type != null && TypeUtils.isAssignable(type, value.getClass())) {
javaType = getJavaType(type, null);
}
ObjectWriter objectWriter = (serializationView != null ?
objectMapper.writerWithView(serializationView) : objectMapper.writer());
if (filters != null) {
objectWriter = objectWriter.with(filters);
}
if (javaType != null && javaType.isContainerType()) {
objectWriter = objectWriter.forType(javaType);
}
SerializationConfig config = objectWriter.getConfig();
if (contentType != null && contentType.isCompatibleWith(MediaType.TEXT_EVENT_STREAM) &&
config.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
objectWriter = objectWriter.with(this.ssePrettyPrinter);
}
//将对象转换为指定的格式
objectWriter.writeValue(generator, value);
writeSuffix(generator, object);
generator.flush();
}
catch (InvalidDefinitionException ex) {
throw new HttpMessageConversionException("Type definition error: " + ex.getType(), ex);
}
catch (JsonProcessingException ex) {
throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getOriginalMessage(), ex);
}
}