Gson bean getxxx,怎么才能返回给前端

使用Gson将Java对象转换为JSON返回给前端,有以下几种常见方式:

1. 基本POJO序列化(推荐)

定义Java Bean

复制代码
public class User {
    private Long id;
    private String name;
    private Integer age;
    private Date createTime;
    
    // Getter/Setter 方法
    public Long getId() {
        return id;
    }
    
    public void setId(Long id) {
        this.id = id;
    }
    
    public 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 Date getCreateTime() {
        return createTime;
    }
    
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

转换为JSON返回

复制代码
@RestController
@RequestMapping("/api")
public class UserController {
    
    @GetMapping("/user")
    public String getUser() {
        User user = new User();
        user.setId(1L);
        user.setName("张三");
        user.setAge(25);
        user.setCreateTime(new Date());
        
        Gson gson = new Gson();
        return gson.toJson(user);
    }
    
    // 或者使用@ResponseBody自动转换
    @GetMapping("/user2")
    @ResponseBody
    public User getUser2() {
        User user = new User();
        user.setId(1L);
        user.setName("李四");
        user.setAge(30);
        return user;
    }
}

2. 使用@SerializedName自定义字段名

复制代码
public class Product {
    @SerializedName("product_id")
    private Long id;
    
    @SerializedName("product_name")
    private String name;
    
    @SerializedName("current_price")
    private Double price;
    
    // Getter/Setter
    public Long getId() {
        return id;
    }
    
    public void setId(Long id) {
        this.id = id;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public Double getPrice() {
        return price;
    }
    
    public void setPrice(Double price) {
        this.price = price;
    }
}

3. 配置Gson实例(日期格式化、空值处理等)

复制代码
@Configuration
public class GsonConfig {
    
    @Bean
    public Gson gson() {
        return new GsonBuilder()
            .setDateFormat("yyyy-MM-dd HH:mm:ss")  // 日期格式化
            .serializeNulls()                     // 序列化null值
            .setPrettyPrinting()                  // 美化输出
            .create();
    }
    
    // 或者使用 excludeFieldsWithoutExposeAnnotation
    @Bean
    public Gson gsonWithExpose() {
        return new GsonBuilder()
            .excludeFieldsWithoutExposeAnnotation()  // 只序列化有@Expose注解的字段
            .create();
    }
}

4. 统一返回结果封装

复制代码
// 统一返回结果类
public class Result<T> {
    private Integer code;
    private String message;
    private T data;
    
    public static <T> Result<T> success(T data) {
        Result<T> result = new Result<>();
        result.setCode(200);
        result.setMessage("success");
        result.setData(data);
        return result;
    }
    
    public static <T> Result<T> error(String message) {
        Result<T> result = new Result<>();
        result.setCode(500);
        result.setMessage(message);
        return result;
    }
    
    // Getter/Setter
    public Integer getCode() {
        return code;
    }
    
    public void setCode(Integer code) {
        this.code = code;
    }
    
    public String getMessage() {
        return message;
    }
    
    public void setMessage(String message) {
        this.message = message;
    }
    
    public T getData() {
        return data;
    }
    
    public void setData(T data) {
        this.data = data;
    }
}

// 控制器中使用
@RestController
@RequestMapping("/api")
public class ApiController {
    
    @Autowired
    private Gson gson;
    
    @GetMapping("/data")
    public String getData() {
        List<User> userList = new ArrayList<>();
        // ... 添加数据
        
        Result<List<User>> result = Result.success(userList);
        return gson.toJson(result);
    }
}

5. 使用@Expose注解控制序列化

复制代码
public class Order {
    @Expose
    private Long id;
    
    @Expose
    private String orderNo;
    
    @Expose(serialize = false)  // 序列化时排除
    private String internalCode;
    
    private String remark;  // 没有@Expose注解,默认不序列化
    
    // Getter/Setter
    public Long getId() {
        return id;
    }
    
    public void setId(Long id) {
        this.id = id;
    }
    
    public String getOrderNo() {
        return orderNo;
    }
    
    public void setOrderNo(String orderNo) {
        this.orderNo = orderNo;
    }
    
    public String getInternalCode() {
        return internalCode;
    }
    
    public void setInternalCode(String internalCode) {
        this.internalCode = internalCode;
    }
    
    public String getRemark() {
        return remark;
    }
    
    public void setRemark(String remark) {
        this.remark = remark;
    }
}

6. Spring Boot中全局配置

复制代码
@Configuration
public class WebConfig implements WebMvcConfigurer {
    
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        GsonHttpMessageConverter gsonConverter = new GsonHttpMessageConverter();
        gsonConverter.setGson(new GsonBuilder()
            .setDateFormat("yyyy-MM-dd HH:mm:ss")
            .create());
        converters.add(gsonConverter);
    }
}

7. 处理特殊需求

排除某些字段

复制代码
public class User {
    private Long id;
    private String name;
    
    @Expose(serialize = false)
    private String password;  // 不序列化密码
    
    // 使用 transient 关键字
    private transient String secretKey;  // 不参与序列化
    
    // Getter/Setter
}

自定义序列化器

复制代码
public class UserSerializer implements JsonSerializer<User> {
    @Override
    public JsonElement serialize(User user, Type type, JsonSerializationContext context) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("id", user.getId());
        jsonObject.addProperty("name", user.getName());
        jsonObject.addProperty("age", user.getAge());
        // 自定义逻辑
        jsonObject.addProperty("description", user.getName() + ",年龄:" + user.getAge());
        return jsonObject;
    }
}

// 注册使用
Gson gson = new GsonBuilder()
    .registerTypeAdapter(User.class, new UserSerializer())
    .create();

8. 前端接收示例

复制代码
// 假设返回的JSON是:
// {
//   "code": 200,
//   "message": "success",
//   "data": {
//     "id": 1,
//     "name": "张三",
//     "age": 25,
//     "createTime": "2024-01-20 10:30:00"
//   }
// }

fetch('/api/user')
  .then(response => response.json())
  .then(data => {
    console.log(data.code);    // 200
    console.log(data.message); // "success"
    console.log(data.data.name); // "张三"
  });

最佳实践建议:

  1. 统一返回格式:使用统一的Result类封装返回结果

  2. 配置全局Gson:在Spring Boot中配置全局Gson实例

  3. 安全性考虑:敏感字段(密码、token等)不要序列化

  4. 性能优化:重用Gson实例,避免频繁创建

  5. 日期格式化:统一日期格式,避免前端解析问题

  6. 使用注解:合理使用@SerializedName、@Expose等注解

相关推荐
vx1_Biye_Design2 小时前
基于Spring Boot+Vue的学生管理系统设计与实现-计算机毕业设计源码46223
java·vue.js·spring boot·spring·eclipse·tomcat·maven
vx_Biye_Design2 小时前
基于Spring Boot+vue的湖北旅游景点门票预约平台的设计--毕设附源码29593
java·vue.js·spring boot·spring cloud·servlet·eclipse·课程设计
hedley(●'◡'●)2 小时前
基于cesium和vue的大疆司空模仿程序
前端·javascript·vue.js·python·typescript·无人机
qq5_8115175152 小时前
web城乡居民基本医疗信息管理系统信息管理系统源码-SpringBoot后端+Vue前端+MySQL【可直接运行】
前端·vue.js·spring boot
百思可瑞教育2 小时前
构建自己的Vue UI组件库:从设计到发布
前端·javascript·vue.js·ui·百思可瑞教育·北京百思教育
百锦再2 小时前
Vue高阶知识:利用 defineModel 特性开发搜索组件组合
前端·vue.js·学习·flutter·typescript·前端框架
hay_lee2 小时前
Spring AI实现对话聊天-流式输出
java·人工智能·ollama·spring ai
Hx_Ma162 小时前
SpringBoot数据源自动管理
java·spring boot·spring
SunnyDays10112 小时前
Java 高效实现 CSV 转 Excel
java·csv转excel
starfire_hit2 小时前
JAVAWEB根据前台请求获取用户IP
java·服务器·网络