Springboot之输出json数据
来源:互联网 发布:access 找不到数据库 编辑:程序博客网 时间:2024/06/01 16:32
接着上一篇的helloworld来说:
可以在pom文件中引入lombok.jar
省去set,get代码
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency>
重新建一个实体类:User
属性:id,name
当然还有其他的,比如
@Getter
@Setter
@RequiredArgConstructor
@ToString
@EqualsAndHashCode
toString都可以省略
然后再在HelloController类中写一个方法:
@RequestMapping("/getUser")public User getUser(){User user = new User();user.setId(1);user.setName("张三");return user;}再次启动访问localhost:8080/getUser 就可以看到json数据了
Springboot默认的使用jackson来处理json数据的,如果我们不想用它默认的,向用fastJson怎么办呢?下面我们就来用下阿里的fastjson处理一下
首先导入fastjson.jar包,版本1.2.10+,根据官方文档说明
第一种方式:
App启动类继承extendsWebMvcConfigurerAdapter
重写:configureMessageConverters 方法
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {//super.configureMessageConverters(converters);/////*// * 1、需要先定义一个 convert 转换消息的对象;// * 2、添加fastJson 的配置信息,比如:是否要格式化返回的json数据;// * 3、在convert中添加配置信息.// * 4、将convert添加到converters当中.// * // */////// 1、需要先定义一个 convert 转换消息的对象;//FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();//////2、添加fastJson 的配置信息,比如:是否要格式化返回的json数据;//FastJsonConfig fastJsonConfig = new FastJsonConfig();//fastJsonConfig.setSerializerFeatures(// SerializerFeature.PrettyFormat// );//////3、在convert中添加配置信息.// fastConverter.setFastJsonConfig(fastJsonConfig);// // //4、将convert添加到converters当中.// converters.add(fastConverter);////}
此时可以在增加一个属性:日期date
@JSONField(format="yyyy-MM-dd HH:mm")private Date date;再次启动访问,此时就是使用了fastjson来处理数据的
第二种方式:
在启动类中 注入Bean : HttpMessageConverters
@Beanpublic HttpMessageConverters fastJsonHttpMessageConverters() {// 1、需要先定义一个 convert 转换消息的对象;FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();//2、添加fastJson 的配置信息,比如:是否要格式化返回的json数据;FastJsonConfig fastJsonConfig = new FastJsonConfig();fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);//3、在convert中添加配置信息.fastConverter.setFastJsonConfig(fastJsonConfig);HttpMessageConverter<?> converter = fastConverter;return new HttpMessageConverters(converter);}
可以达到同样的效果
阅读全文
0 0
- Springboot之输出json数据
- SpringBoot返回json数据
- springboot第一天 快速启动,json输出
- 【系统学习SpringBoot】SpringBoot 对象转JSON输出
- SpringBoot之数据访问
- 复杂JSON输出数据
- action输出json数据
- JSON数据的输出
- 输出json格式数据
- 格式化输出json数据
- SpringBoot使用FastJson解析Json数据
- SpringBoot入门-3(返回json数据)
- SpringBoot之数据访问操作
- 服务器端输出 JSON 格式数据
- 服务器端输出 JSON 格式数据
- PHP格式化输出json数据
- php正确输出json数据
- go json数据格式化输出
- iOS 应用获取最上层全屏 Window 的正确方法
- YII2.0 表单组件的使用方法
- VS2013编译错误:未处理FileLoadException
- Yii Html::a 当参数是数组的时候
- fridge11_28:Git的安装和使用
- Springboot之输出json数据
- URL编码
- Git的使用
- 文件输入输出流(复制文本,视频,音频,图片的多种方式)
- C语言之#include用法详解
- sqlite3数据库命令简介(C语言环境)
- 运行时多态和编译时多态
- Toobar标题文字居中解决方案
- 通过web service查询天气