使用spring boot开发时java对象和Json对象转换的问题
将java对象转换为json对象,市面上有很多第三方jar包,如下:
jackson(最常用)
com.fasterxml.jackson.core jackson-databind 2.11.2
gson
com.google.code.gson gson 2.8.5
fastjson
com.alibaba fastjson 1.2.62
一、构建测试项目
开发工具为:IDEA
后端技术:Springboot,Maven
引入依赖
4.0.0 org.springframework.boot spring-boot-starter-parent 2.4.3 com.example json 0.0.1-SNAPSHOT json DemoprojectforSpringBoot 1.8 org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-web org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin org.projectlombok lombok
可以从上面看出,并未引入Jackson相关依赖,这是因为Springboot的起步依赖spring-boot-starter-web已经为我们传递依赖了JacksonJSON库。
当我们不用它,而采用其他第三方jar包时,我们可以排除掉它的依赖,可以为我们的项目瘦身。
org.springframework.boot spring-boot-starter-web jackson-core com.fasterxml.jackson.core
二、jackson转换
1.构建User实体类
importlombok.AllArgsConstructor;
importlombok.Data;
importlombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
publicclassUserEntity{
privateStringuserName;
privateintage;
privateStringsex;
}
代码如下(示例):
importnumpyasnp
importpandasaspd
importmatplotlib.pyplotasplt
importseabornassns
importwarnings
warnings.filterwarnings('ignore')
importssl
ssl._create_default_https_context=ssl._create_unverified_context
2.controller类
Java对象转换为json对象
@Controller
publicclassJsonController{
@GetMapping("/json1")
//思考问题,正常返回它会走视图解析器,而json需要返回的是一个字符串
//市面上有很多的第三方jar包可以实现这个功能,jackson,只需要一个简单的注解就可以实现了
//@ResponseBody,将服务器端返回的对象转换为json对象响应回去
@ResponseBody
publicStringjson1()throwsJsonProcessingException{
//需要一个jackson的对象映射器,就是一个类,使用它可以将对象直接转换成json字符串
ObjectMappermapper=newObjectMapper();
//创建对象
UserEntityuserEntity=newUserEntity("笨笨熊",18,"男");
System.out.println(userEntity);
//将java对象转换为json字符串
Stringstr=mapper.writeValueAsString(userEntity);
System.out.println(str);
//由于使用了@ResponseBody注解,这里会将str以json格式的字符串返回。
returnstr;
}
@GetMapping("/json2")
@ResponseBody
publicStringjson2()throwsJsonProcessingException{
ArrayListuserEntities=newArrayList<>();
UserEntityuser1=newUserEntity("笨笨熊",18,"男");
UserEntityuser2=newUserEntity("笨笨熊",18,"男");
UserEntityuser3=newUserEntity("笨笨熊",18,"男");
userEntities.add(user1);
userEntities.add(user2);
userEntities.add(user3);
returnnewObjectMapper().writeValueAsString(userEntities);
}
}
Date对象转换为json对象
@GetMapping("/json3")
@ResponseBody
publicStringjson3()throwsJsonProcessingException{
ObjectMappermapper=newObjectMapper();
//Date默认返回时间戳,所以需要关闭它的时间戳功能
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
//时间格式化问题自定义时间格式对象
SimpleDateFormatsimpleDateFormat=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss");
//让mapper指定时间日期格式为simpleDateFormat
mapper.setDateFormat(simpleDateFormat);
//写一个时间对象
Datedate=newDate();
returnmapper.writeValueAsString(date);
}
提取工具类JsonUtils
publicclassJsonUtils{
publicstaticStringgetJson(Objectobject){
returngetJson(object,"yyyy-MM-ddHH:mm:ss");
}
publicstaticStringgetJson(Objectobject,StringdateFormat){
ObjectMappermapper=newObjectMapper();
//Date默认返回时间戳,所以需要关闭它的时间戳功能
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
//时间格式化问题自定义时间格式对象
SimpleDateFormatsimpleDateFormat=newSimpleDateFormat(dateFormat);
//让mapper指定时间日期格式为simpleDateFormat
mapper.setDateFormat(simpleDateFormat);
try{
returnmapper.writeValueAsString(object);
}catch(JsonProcessingExceptione){
e.printStackTrace();
}
returnnull;
}
}
优化后:
@GetMapping("/json4")
@ResponseBody
publicStringjson4()throwsJsonProcessingException{
Datedate=newDate();
returnJsonUtils.getJson(date);
}
三、gson转换
引入上述gson依赖
Controller类
@RestController
publicclassgsonController{
@GetMapping("/gson1")
publicStringjson1()throwsJsonProcessingException{
ArrayListuserEntities=newArrayList<>();
UserEntityuser1=newUserEntity("笨笨熊",18,"男");
UserEntityuser2=newUserEntity("笨笨熊",18,"男");
UserEntityuser3=newUserEntity("笨笨熊",18,"男");
userEntities.add(user1);
userEntities.add(user2);
userEntities.add(user3);
Gsongson=newGson();
Stringstr=gson.toJson(userEntities);
returnstr;
}
}
四、fastjson转换
引入相关依赖
Controller类
@RestController
publicclassFastJsonController{
@GetMapping("/fastjson1")
publicStringjson1()throwsJsonProcessingException{
ArrayListuserEntities=newArrayList<>();
UserEntityuser1=newUserEntity("笨笨熊",18,"男");
UserEntityuser2=newUserEntity("笨笨熊",18,"男");
UserEntityuser3=newUserEntity("笨笨熊",18,"男");
userEntities.add(user1);
userEntities.add(user2);
userEntities.add(user3);
Stringstr=JSON.toJSONString(userEntities);
returnstr;
}
}
到此这篇关于使用springboot开发时java对象和Json对象转换的问题的文章就介绍到这了,更多相关springbootjava对象和Json对象转换内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。