我们都知道一个spring boot的主要作用就是为了接口的实现,接口的实现当中少不了对于Jeson的运用
接下来就是我们第一个关于Jeson接口的实现(其中模型、协议相关内容就不展示了)
package com.example.demo;
import com.google.gson.Gson; //关于Gsonde的包引用
import model.Human;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/BaseBusiness")
public class BaseBusiness {
@RequestMapping("/Index")
public String Index() {
return "Hello Business";
}
@RequestMapping("/ShowEnterJeson")
public String ShowEnterJeson(@RequestBody String str){
//声明Gson对象
Gson gson = new Gson();
//利用方法fromJson对Json进行转换()
String reslt = gson.fromJson(str, String.class);
return str+"<br>"+reslt;
}
@RequestMapping("/HumanToJeson")
public String HumanToJeson(@RequestBody String str){
String result="";
Gson gson = new Gson();
//对Json进行转换(转换成模型对象)
Human human=gson.fromJson(str, Human.class);
result+=("姓名为:"+ human.name+"\n");
result+=("年龄为:"+ human.age+"\n");
result+=("性别为:"+ human.sex+"\n");
return result;
}
}
对于喜欢使用Maven的程序可以使用下面的配置载入Gson库
pom.xml文件配置(放到<dependencies>里面后up项目即可)
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>
更多关于Gson的用可以访问下面地址
Gson下载:https://blog.csdn.net/qq_29503199/article/details/91420109
Java当中Gson的使用:https://blog.csdn.net/qq_29503199/article/details/90713025