Java中使用GSON序列化对象显示时如何去除多余转义反斜杠
问题原因
- 重复JSON序列化:你先手动用Gson把每个Book对象转成了JSON字符串,得到字符串数组后,Spring MVC会用内置的Jackson序列化器再次对整个返回值做JSON序列化,原JSON字符串里的双引号会被转义,所以出现了大量
\"。 - 最后一条为null的bug:
AddBook方法的判断逻辑错误,你用id == len作为越界判断条件,当传入id=6时刚好等于len=6,所以返回null,导致最后一个元素为null。 - 补充:Book类的属性都是私有且没有提供公共getter方法,后续直接返回对象序列化时可能无法正常读取属性值。
解决方案
最优方案(推荐):直接返回Book对象数组,交由Spring自动序列化
你完全不需要手动调用Gson做序列化,Spring MVC会自动帮你把返回的对象序列化为标准JSON,步骤如下:
- 给Book类添加Getter方法
public class Book { private int id; private String name; private String type; private boolean available; public Book(int id, String name, String type, boolean available) { super(); this.id = id; this.name = name; this.type = type; this.available = available; } // 新增Getter方法 public int getId() { return id; } public String getName() { return name; } public String getType() { return type; } public boolean isAvailable() { return available; } @Override public String toString() { return "{id=" + id + ", name=" + name + ", type=" + type + ", available=" + available + "},"; } }
- 修复BookService里AddBook的越界判断逻辑
public Book AddBook(int id, String name, String type, boolean available) { // 把原来的id==len判断改成判断当前存储数量是否超过数组长度 if(size >= len) return null; this.size++; return Allbooks[this.size - 1] = createBook(id, name, type, available); } // 新增直接返回Book数组的方法 public Book[] getAllBooks() { bookRepo(); return Allbooks; }
- 修改Controller的返回类型为Book[]
@GetMapping(path = "/books") public Book[] getAllBooks() { return bookRepository.getAllBooks(); }
修改后调用接口就能得到你预期的无转义标准JSON数组。
如果你坚持要使用Gson手动序列化
可以直接把整个Book数组一次性转为JSON字符串,然后返回给前端,同时指定返回的内容类型:
@GetMapping(path = "/books", produces = "application/json; charset=utf-8") public String getAllBooks() { bookRepository.bookRepo(); return new Gson().toJson(bookRepository.Allbooks); }
这种方式Spring会直接把返回的字符串作为JSON内容返回,不会做二次序列化,也不会出现转义符。
内容的提问来源于stack exchange,提问作者Mile Stanislavov
相关产品推荐
相关产品推荐

