日常使用中,API需要使用到JSON操作,JSON相关操作可以使用Gson,虽然阿里有FastJson,但是执行效率和底层实现上GSON具有明显优势,网站可能需要使用到模板引擎,模板引擎使用thymeleaf。
关于一些数据类操作,可以使用lombok来提高操作效率。
各个的pom依赖:
org.springframework.boot spring-boot-starter-thymeleaf org.projectlombok lombok true com.google.code.gson gson 2.8.6
thymeleaf
thymeleaf使用,需要在模板中加入标签
控制器上,可以在具体的方法上加上Model,使用model.addAttribute("key",val);来对模板变量进行赋值,接着return一个模板文件路径即可。
引擎配置:可以在resources/application.properties中写入全局配置信息:
# 模板路径 spring.thymeleaf.prefix=classpath:/templates/ # 模板扩展名 spring.thymeleaf.suffix=.html # 其他 spring.thymeleaf.mode=HTML5 spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.content-type=text/html # 是否缓存 spring.thymeleaf.cache=false spring.thymeleaf.check-template-location=true
关于thymeleaf模板标签更多内容,点击这里
GSON
//实例化
Gson gson = new Gson();
//实例化
user u = user.builder().name("张三").id(1).age(25).build();
//序列化JSON(对象)
String json = gson.toJson(u);
//反序列化到对象
u = gson.fromJson(json,user.class);
//序列化JSON(数组)
List userList = new ArrayList<>();
userList.add(u);
json = gson.toJson(userList);
//反序列化(数组)
Type type = new TypeToken>() {}.getType();
List lists = gson.fromJson(json,type);
lombok
package com.example.demo.model;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class user {
private String name;
private int age;
private int id;
}
可以在数据类上写上@Data注解,来实现自动处理,写@Builder注解,即可通过builder()快速实例化设置数据类。



