当前位置: 首页> 科技> 能源 > 中山网站关键词排名_上海本地新闻_2345网址导航官网下载安装_常见的搜索引擎有哪些

中山网站关键词排名_上海本地新闻_2345网址导航官网下载安装_常见的搜索引擎有哪些

时间:2025/7/10 3:39:23来源:https://blog.csdn.net/zp357252539/article/details/147049325 浏览次数:0次
中山网站关键词排名_上海本地新闻_2345网址导航官网下载安装_常见的搜索引擎有哪些

以下是关于Spring MVC处理JSON数据集的详细说明,涵盖如何接收和发送JSON数据,包含代码示例和总结表格:


1. 核心机制

Spring MVC通过以下方式支持JSON数据的传输:

  1. 接收JSON数据:使用@RequestBody注解将HTTP请求体中的JSON自动转换为Java对象。
  2. 发送JSON数据:通过@RestController@ResponseBody注解将Java对象序列化为JSON响应。

2. 代码示例

2.1 实体类定义
// 用户实体类(与JSON结构对应)
public class User {private String name;private Integer age;private String email;// 构造函数、getter和setter方法public User() {}public User(String name, Integer age, String email) {this.name = name;this.age = age;this.email = email;}// Getters and Setterspublic String getName() { return name; }public void setName(String name) { this.name = name; }public Integer getAge() { return age; }public void setAge(Integer age) { this.age = age; }public String getEmail() { return email; }public void setEmail(String email) { this.email = email; }
}

2.2 Controller类
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/api")
public class UserController {// 接收JSON数据并返回响应@PostMapping("/user")public User createUser(@RequestBody User user) {// 业务逻辑(如保存用户)return user; // 自动序列化为JSON}// 发送JSON响应@GetMapping("/user/{id}")public User getUser(@PathVariable String id) {// 模拟从数据库获取用户return new User("John Doe", 30, "john@example.com");}
}

2.3 前端请求示例(JavaScript)
// 发送POST请求(提交JSON数据)
fetch('/api/user', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify({name: 'Alice',age: 25,email: 'alice@example.com'})
})
.then(response => response.json())
.then(data => console.log('Success:', data));// 发送GET请求(获取JSON数据)
fetch('/api/user/123')
.then(response => response.json())
.then(data => console.log('User:', data));

3. 关键点说明

  1. @RequestBody注解

    • 作用:将HTTP请求体中的JSON数据自动反序列化为Java对象。
    • 要求
      • 请求头Content-Type必须为application/json
      • 实体类需提供无参构造函数和setter方法。
  2. Jackson库的作用

    • Spring默认使用Jackson进行JSON序列化/反序列化。
    • 支持复杂类型(如嵌套对象、集合)。
  3. 字段映射规则

    • 默认:JSON字段名与Java对象属性名需一致(不区分大小写)。
    • 自定义映射:通过@JsonProperty注解指定JSON字段名:
      public class User {@JsonProperty("user_email") // 映射JSON字段"email"到"user_email"private String email;
      }
      
  4. 集合和嵌套对象

    // 示例:用户包含地址信息
    public class User {private String name;private Address address; // 嵌套对象private List<String> hobbies; // 集合// ...
    }public class Address {private String city;private String zipcode;// ...
    }
    

4. 常见问题与解决

问题解决方案
JSON字段名与Java属性名不一致使用@JsonProperty("json_field_name")显式映射。
日期格式不匹配(如"yyyy-MM-dd")使用@JsonFormat(pattern = "yyyy-MM-dd")或自定义序列化器/反序列化器。
空值字段被序列化为null使用@JsonInclude(JsonInclude.Include.NON_NULL)排除空值。
复杂对象嵌套(如List<User>确保嵌套对象有无参构造函数和setter方法。

5. 总结表格

功能实现方式示例说明
接收JSON数据@RequestBody User userPOST /user → {"name": "Alice", "age": 25}User对象自动反序列化,需匹配字段名。
发送JSON响应@RestController@ResponseBodyGET /user/123 → {"name": "John", "age": 30}自动序列化Java对象为JSON。
自定义字段映射@JsonProperty("json_field")@JsonProperty("email") private String userEmail → JSON字段email映射到userEmail
排除空值字段@JsonInclude(JsonInclude.Include.NON_NULL)@JsonInclude在类上标注 → 空字段不输出。
处理日期格式@JsonFormat(pattern = "yyyy-MM-dd")@JsonFormat(pattern="yyyy-MM-dd") Date birth → JSON格式"2023-01-01"

6. 完整代码示例

实体类:User.java
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;@JsonInclude(JsonInclude.Include.NON_NULL) // 排除空值字段
public class User {private String name;private Integer age;@JsonProperty("user_email") // 映射JSON字段"email"到"user_email"private String email;// 构造函数、getter和setter
}
Controller类:UserController.java
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/api")
public class UserController {// 接收JSON并返回响应@PostMapping("/user")public User createUser(@RequestBody User user) {// 业务逻辑return user;}// 发送带日期的JSON响应@GetMapping("/date")public DateResponse getDate() {Date now = new Date();return new DateResponse(now);}
}// 带日期的响应类
class DateResponse {@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")private Date timestamp;public DateResponse(Date date) {this.timestamp = date;}// getter方法
}
测试请求(curl)
# 发送POST请求
curl -X POST \http://localhost:8080/api/user \-H 'Content-Type: application/json' \-d '{"name": "Alice", "age": 25, "email": "alice@example.com"}'# 发送GET请求获取日期
curl http://localhost:8080/api/date
# 返回:{"timestamp": "2023-10-05 14:30:00"}

7. 注意事项

  • 依赖管理:Spring Boot默认包含Jackson依赖,无需额外添加。
  • 复杂对象:确保嵌套对象和集合有合适的构造函数和getter/setter。
  • 安全性:避免直接暴露敏感字段(如密码),使用@JsonIgnore注解排除敏感数据。

通过@RequestBody@RestController,Spring MVC可高效处理JSON数据的双向传输,满足前后端分离的开发需求。

关键字:中山网站关键词排名_上海本地新闻_2345网址导航官网下载安装_常见的搜索引擎有哪些

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: