You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Controller无法解析HttpClient发送的JSON:无法构造LinkedHashMap实例

问题:HttpClient发送JSON到Spring控制器解析失败

场景说明

使用java.net.http.HttpClient向Spring控制器发送JSON对象,控制器以Map<String, Object>接收请求体。JSON格式合法,Postman发送可正常接收,但HttpClient发送时出现解析错误。

待发送的JSON内容:

{"fruit": "Apple", "color": "Red"}

原客户端请求代码

ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
String jsonString = mapper.writeValueAsString(body);

HttpRequest request = HttpRequest.newBuilder()
    .uri(new URI(url))
    .header("content-type", "application/json")
    .POST(BodyPublishers.ofString(jsonString))
    .build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());

Spring控制器代码

@PostMapping(value = "/config/addDocument", consumes = {"application/json"})
public void addDocument(@RequestBody Map<String, Object> document)

报错信息

HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `java.util.LinkedHashMap` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{"fruit": "Apple", "color": "Red"}'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `java.util.LinkedHashMap` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{"fruit": "Apple", "color": "Red"}')
 at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 1]]

补充信息

  • 客户端为java.net.http.HttpClient,通过HttpClient.newHttpClient()实例化
  • 使用Spring Boot Starter Web 2.7.5版本

解决方法

将输入的JSON字符串先反序列化为Map,再重新序列化为JSON字符串后发送,即可解决问题。修改后的代码如下:

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(body, Map.class);
String jsonString = mapper.writeValueAsString(map);

HttpRequest request = HttpRequest.newBuilder()
    .uri(new URI(url))
    .header("content-type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString(jsonString))
    .build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());

内容的提问来源于stack exchange,提问作者Yoh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 10:30:56