后端技术栈之FastJson
框架介绍
@Data:作用于类上,是以下注解的集合:@ToString @EqualsAndHashCode @Getter @Setter @RequiredArgsConstructor
框架使用
在domin文件夹下新建Book.java类
@Data
public class Book {
private String name;
private String author;
private Float price;
}
在controller文件夹下新建BookController.java类
@RestController
public class BookController {
@GetMapping("/book")
public Book book(){
Book b1 = new Book();
b1.setAuthor("罗贯中");
b1.setName("三国演义");
b1.setPrice(18.3f);
return b1;
}
}
在pom.xml文件夹中添加FastJson依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
新建mFastJsonConfig.java文件修改FastJson配置。
@Configuration
public class mFastJsonConfig {
@Bean
FastJsonHttpMessageConverter fastJsonHttpMessageConverter(){
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setDateFormat("yyyy-MM-dd");
config.setCharset(Charset.forName("UTF-8"));
config.setSerializerFeatures(
SerializerFeature.WriteClassName,
SerializerFeature.WriteMapNullValue,
SerializerFeature.PrettyFormat,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullStringAsEmpty
);
converter.setFastJsonConfig(config);
return converter;
}
}
在application.properties中添加如下配置:
## FastJson
server.servlet.encoding.force-response=true
运行项目,在浏览器中输入网址:
http://localhost:8080/book
运行显示:
{ "@type":"com.suromo.springdemo.domain.Book", "author":"罗贯中", "name":"三国演义", "price":18.3F }
成功获取json数据。