JSF前端通过Jersey调用Spring Boot后端POST接口JSON反序列化报错
解决Jersey Client POST请求JSON到Spring Boot后端的反序列化错误
问题根源分析
从报错信息来看,后端Jackson试图把完整的JSON字符串 '{"id":0,"name":"abc","city":"def","contactNum":334455}' 当成单个String值去反序列化成Customer对象,但你的Customer类没有接受单个String参数的构造方法,所以抛出了这个错误。
出现这种情况的核心原因是:你的前端代码把对象转成JSON字符串后,没有正确设置请求的Content-Type为application/json,且以普通文本形式发送了JSON字符串,导致后端误以为你要传递的是一个String类型参数,而非JSON格式的Customer对象。
解决方案
这里提供两种可行的修复方式,你可以根据需求选择:
方式1:修正现有Gson序列化的发送逻辑
手动转成JSON字符串后,明确设置请求的Content-Type,并将字符串作为JSON实体发送:
public static void saveCustomer(Customer customer) throws IOException { Gson gson = new Gson(); String custJson = gson.toJson(customer); System.out.println(custJson); Client client = Client.create(); WebResource webResource = client.resource("http://你的后端接口地址/customers"); // 关键步骤:指定请求体类型为application/json ClientResponse response = webResource .type(MediaType.APPLICATION_JSON) .post(ClientResponse.class, custJson); // 后续响应处理逻辑 client.destroy(); }
方式2:使用Jersey自带JSON Provider自动序列化对象
无需手动用Gson转换,让Jersey帮你完成对象到JSON的序列化,更简洁且不易出错。首先确保项目引入了jersey-json依赖,然后直接传递Customer对象:
public static void saveCustomer(Customer customer) throws IOException { Client client = Client.create(); // 注册JSON Provider,让Jersey自动处理序列化/反序列化 client.addFilter(new JacksonJaxbJsonProvider()); WebResource webResource = client.resource("http://你的后端接口地址/customers"); // 直接传递Customer对象,Jersey会自动转成JSON并设置正确的Content-Type ClientResponse response = webResource .type(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .post(ClientResponse.class, customer); // 后续响应处理逻辑 client.destroy(); }
后端额外检查点
虽然报错提示"至少一个Creator存在",但还是建议确认你的Customer类满足Jackson反序列化要求:
- 包含无参构造方法(Jackson默认依赖该构造方法实例化对象)
- 所有字段有对应的getter/setter方法(或字段为public,更推荐用getter/setter)
示例Customer类结构:
public class Customer { private Integer id; private String name; private String city; private Long contactNum; // 必须存在的无参构造方法 public Customer() {} // 全参构造方法(可选,若使用@JsonCreator需配合@JsonProperty注解) public Customer(Integer id, String name, String city, Long contactNum) { this.id = id; this.name = name; this.city = city; this.contactNum = contactNum; } // 所有字段的getter和setter public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public Long getContactNum() { return contactNum; } public void setContactNum(Long contactNum) { this.contactNum = contactNum; } }
内容的提问来源于stack exchange,提问作者Kasun Hasanka
相关产品推荐
相关产品推荐

