• Spring Boot中JSON的数据结构和交互讲解以及实战(超详细 附源码)


    Spring MVC在数据绑定的过程中,需要对传递数据的格式和类型进行转换,它既可以转换String登类型的数据,也可以转换JSON等其他类型的数据。

    JSON数据结构

    JSON(JavaScript Object Notation JS对象标记)是一种轻量级的数据交换格式,与XML一样,JSON也是基于纯文本的数据格式 它有以下两种数据结构

    1:对象结构

    对象结构以{开始 }结束,中间部分由0个或多个以英文,分割的key/value对构成,key和value之间以英文:分割,语法结构如下

    {

    key1:value1,

    key2:value2,

    ...

    }

    2:数组结构

    数组结构以[开始以]结束,中间部分由0个活多个以英文,分割的值的列表组成 语法结构如下

    [

    value1,

    value2.

    ...

    JSON数据转换 

    为实现浏览器与控制器类之间的JSON数据交互,Spring MVC提供了MappingJackson2HttpMessageConverter实现类默认处理JSON格式请求响应。该实现类利用Jackson开源包读取JSON数据,将Java对象转换为JSON对象和XML文档,同时也可以将JSON对象和XML文档转换为Java对象

    在使用注解开发时,需要用到两个重要的JSON格式转换注解

    1:@RequestBody

    用于将请求体的数据绑定到方法的形参上,该注解应用在方法的形参上

    2:@ResponseBody

    用于直接返回JSON对象 该注解应用在方法上

    下面通过一个实例来演示JSON数据交互过程

    1:创建Web应用ch2_5并导入JAR包

    2:创建Web和Spring MVC配置类

    Webconfig类代码如下

    1. package config;
    2. import javax.servlet.ServletContext;
    3. import javax.servlet.ServletException;
    4. import javax.servlet.ServletRegistration.Dynamic;
    5. import org.springframework.web.WebApplicationInitializer;
    6. import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
    7. import org.springframework.web.servlet.DispatcherServlet;
    8. public class WebConfig implements WebApplicationInitializer{
    9. @Override
    10. public void onStartup(ServletContext arg0) throws ServletException {
    11. AnnotationConfigWebApplicationContext ctx
    12. = new AnnotationConfigWebApplicationContext();
    13. ctx.register(SpringMVCConfig.class);//注册Spring MVC的Java配置类SpringMVCConfig
    14. ctx.setServletContext(arg0);//和当前ServletContext关联
    15. /**
    16. * 注册Spring MVC的DispatcherServlet
    17. */
    18. Dynamic servlet = arg0.addServlet("dispatcher", new DispatcherServlet(ctx));
    19. servlet.addMapping("/");
    20. servlet.setLoadOnStartup(1);
    21. }
    22. }

    SpringMVCConfig类代码如下

    1. package config;
    2. import org.springframework.context.annotation.Bean;
    3. import org.springframework.context.annotation.ComponentScan;
    4. import org.springframework.context.annotation.Configuration;
    5. import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    6. import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    7. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    8. import org.springframework.web.servlet.view.InternalResourceViewResolver;
    9. @Configuration
    10. @EnableWebMvc
    11. @ComponentScan("controller")
    12. public class SpringMVCConfig implements WebMvcConfigurer {
    13. /**
    14. * 配置视图解析器
    15. */
    16. @Bean
    17. public InternalResourceViewResolver getViewResolver() {
    18. InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    19. viewResolver.setPrefix("/WEB-INF/jsp/");
    20. viewResolver.setSuffix(".jsp");
    21. return viewResolver;
    22. }
    23. /**
    24. * 配置静态资源
    25. */
    26. @Override
    27. public void addResourceHandlers(ResourceHandlerRegistry registry) {
    28. registry.addResourceHandler("/js/**").addResourceLocations("/js/");
    29. }
    30. }

    3:创建JSP页面 并引入jQuery

    首先去官方网站http://jquery.com/download/下载jQuery插件 然后复制到WebContent目录下

    创建JSP文件index.jsp 代码如下

    1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    2. <!DOCTYPE html>
    3. <html>
    4. <head>
    5. <meta charset="UTF-8">
    6. <title>Insert title here</title>
    7. <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-3.2.1.min.js"></script>
    8. <script type="text/javascript">
    9. function testJson() {
    10. //获取输入的值pname为id
    11. var pname = $("#pname").val();
    12. var password = $("#password").val();
    13. var page = $("#page").val();
    14. $.ajax({
    15. //请求路径
    16. url : "${pageContext.request.contextPath }/testJson",
    17. //请求类型
    18. type : "post",
    19. //data表示发送的数据
    20. data : JSON.stringify({pname:pname,password:password,page:page}),
    21. //定义发送请求的数据格式为JSON字符串
    22. contentType : "application/json;charset=utf-8",
    23. //定义回调响应的数据格式为JSON字符串,该属性可以省略
    24. dataType : "json",
    25. //成功响应的结果
    26. success : function(data){
    27. if(data != null){
    28. //返回一个Person对象
    29. //alert("输入的用户名:" + data.pname + ",密码:" + data.password + ",年龄:" + data.page);
    30. //ArrayList<Person>对象
    31. /**for(var i = 0; i < data.length; i++){
    32. alert(data[i].pname);
    33. }**/
    34. //返回一个Map<String, Object>对象
    35. //alert(data.pname);//pname为key
    36. //返回一个List<Map<String, Object>>对象
    37. for(var i = 0; i < data.length; i++){
    38. alert(data[i].pname);
    39. }
    40. }
    41. }
    42. });
    43. }
    44. </script>
    45. </head>
    46. <body>
    47. <form action="">
    48. 用户名:<input type="text" name="pname" id="pname"/><br>
    49. 密码:<input type="password" name="password" id="password"/><br>
    50. 年龄:<input type="text" name="page" id="page"/><br>
    51. <input type="button" value="测试" onclick="testJson()"/>
    52. </form>
    53. </body>
    54. </html>

    4:创建实体类

    在src目录上创建pojo包并创建Person实体类

    1. package pojo;
    2. public class Person {
    3. private String pname;
    4. private String password;
    5. private Integer page;
    6. public String getPname() {
    7. return pname;
    8. }
    9. public void setPname(String pname) {
    10. this.pname = pname;
    11. }
    12. public String getPassword() {
    13. return password;
    14. }
    15. public void setPassword(String password) {
    16. this.password = password;
    17. }
    18. public Integer getPage() {
    19. return page;
    20. }
    21. public void setPage(Integer page) {
    22. this.page = page;
    23. }
    24. }

    5:创建控制器类

    TestController类代码如下

    1. package controller;
    2. import java.util.ArrayList;
    3. import java.util.HashMap;
    4. import java.util.List;
    5. import java.util.Map;
    6. import org.springframework.stereotype.Controller;
    7. import org.springframework.web.bind.annotation.RequestBody;
    8. import org.springframework.web.bind.annotation.RequestMapping;
    9. import org.springframework.web.bind.annotation.ResponseBody;
    10. import pojo.Person;
    11. @Controller
    12. public class TestController {
    13. /**
    14. * 接收页面请求的JSON数据,并返回JSON格式结果
    15. */
    16. @RequestMapping("/testJson")
    17. @ResponseBody
    18. public List<Map<String, Object>> testJson(@RequestBody Person user) {
    19. //打印接收的JSON格式数据
    20. System.out.println("pname=" + user.getPname() +
    21. ", password=" + user.getPassword() + ",page=" + user.getPage());
    22. //返回Person对象
    23. //return user;
    24. /**ArrayList<Person> allp = new ArrayList<Person>();
    25. Person p1 = new Person();
    26. p1.setPname("陈恒1");
    27. p1.setPassword("123456");
    28. p1.setPage(80);
    29. allp.add(p1);
    30. Person p2 = new Person();
    31. p2.setPname("陈恒2");
    32. p2.setPassword("78910");
    33. p2.setPage(90);
    34. allp.add(p2);
    35. //返回ArrayList<Person>对象
    36. return allp;
    37. **/
    38. Map<String, Object> map = new HashMap<String, Object>();
    39. map.put("pname", "陈恒2");
    40. map.put("password", "123456");
    41. map.put("page", 25);
    42. //返回一个Map<String, Object>对象
    43. //return map;
    44. //返回一个List<Map<String, Object>>对象
    45. List<Map<String, Object>> allp = new ArrayList>();
    46. allp.add(map);
    47. Map<String, Object> map1 = new HashMap<String, Object>();
    48. map1.put("pname", "陈恒3");
    49. map1.put("password", "54321");
    50. map1.put("page", 55);
    51. allp.add(map1);
    52. return allp;
    53. }
    54. }

    6:测试应用

    选择Run命令发布并运行应用即可

  • 相关阅读:
    利用AI Chat 将电子书自动截屏并保存成pdf文件
    C++串模式匹配实验
    WPF入门教程系列二十八 ——DataGrid使用示例MVVM模式(6)
    3D人脸关键点和重构调研
    知识蒸馏算法汇总
    java版工程管理系统Spring Cloud+Spring Boot+Mybatis实现工程管理系统
    利用 Kubernetes 内置 PodTemplate 管理 Jenkins 构建节点
    Springboot毕设项目基于SpringBoot的演唱会购票系统z2673(java+VUE+Mybatis+Maven+Mysql)
    利用函数指针数组写计算器(转移表)
    【AI绘画】Stable Diffusion WebUI
  • 原文地址:https://blog.csdn.net/jiebaoshayebuhui/article/details/127645935