情景:
通过@ResponseBody
注解返回json数据,通常返回的是一个Object,spring会自动将Object转化为json字符串。但是在某些时候,我希望对返回的json做进一步处理,比如再次封装一下,那么在springboot中可以通过@JsonComponent
注解来处理
用法:
@JsonComponent
public class Json {
public static class Serializer extends JsonSerializer<Object> {
// arg0 即是Controller返回的对象
// arg1 即是输出对象
@Override
public void serialize(Object arg0, JsonGenerator arg1, SerializerProvider arg2) throws IOException {
// 新的map
Map<String, Object> map = new HashMap<>(2);
// 添加自定义值
map.put("a", "这是一个处理添加参数");
// 添加原返回值
map.put("base", arg0);
// 输出
arg1.writeString(new ObjectMapper().writeValueAsString(map));
// 使用以上方法默认会转义引号等符号,可以使用 writeRaw 方法进行输出
// raw 即未加工的 不会改变格式
// 1.使用自带解析器
// writeRaw(new ObjectMapper().writeValueAsString(map));
// 2.使用FastJson
// arg1.writeRaw (JSON.toJSONString(map));
}
}
}
注意:此配置类需被spring扫描到