失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 5.spring boot使用FastJson解析JSON数据

5.spring boot使用FastJson解析JSON数据

时间:2023-11-07 23:26:25

相关推荐

5.spring boot使用FastJson解析JSON数据

独角兽企业重金招聘Python工程师标准>>>

1.引入FastJson依赖包

<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.47</version></dependency>

2.在Application配置FastJson

package com.text.textdemo;import com.alibaba.fastjson.serializer.SerializerFeature;import com.alibaba.fastjson.support.config.FastJsonConfig;import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.autoconfigure.http.HttpMessageConverters;import org.springframework.context.annotation.Bean;import org.springframework.http.MediaType;import org.springframework.http.converter.HttpMessageConverter;import java.util.ArrayList;import java.util.List;@SpringBootApplicationpublic class TextDemoApplication {public static void main(String[] args) {SpringApplication.run(TextDemoApplication.class, args);}@Beanpublic HttpMessageConverters fastJsonHttpMessageConverters() {//1.需要先定义一个Convert 转换消息的对象;FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();//2.添加fastjson的配置信息,比如:是否要格式化返回就送数据;FastJsonConfig fastJsonConfig = new FastJsonConfig();fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);//3.在Convert中添加配置信息;fastConverter.setFastJsonConfig(fastJsonConfig);//解决中文乱码List<MediaType> fastMediaTypes = new ArrayList<>();fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);fastConverter.setSupportedMediaTypes(fastMediaTypes);HttpMessageConverter<?> converter = fastConverter;return new HttpMessageConverters(converter);}}

3.编写测试Demo实体类

package com.text.textdemo;import com.alibaba.fastjson.annotation.JSONField;import java.util.Date;public class Demo {private int id;private String name;//创建时间 格式化时间@JSONField(format = "yyyy-MM-dd HH:mm")private Date createTime;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Date getCreateTime() {return createTime;}public void setCreateTime(Date createTime) {this.createTime = createTime;}}

4.编写测试getDemo方法

@RequestMapping(value = "/getDemo" ,method = RequestMethod.GET)public Demo getDemo(){Demo demo = new Demo();demo.setId(1);demo.setName("您好,spring boot");demo.setCreateTime(new Date());return demo;}

5.测试

总结:如果不想返回实体的属性,请在属性什么加上@JSONField(serialize = false)

如果觉得《5.spring boot使用FastJson解析JSON数据》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。