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

Spring RestController返回Google JsonElement报错求助

问题分析与解决方案

你遇到的大概率是**HttpMessageNotWritableException**,报错信息通常会包含类似"Could not write JSON: No serializer found for class com.google.gson.JsonElement..."的内容。

原因

Spring MVC默认使用Jackson作为JSON序列化/反序列化工具,但JsonElement是Google Gson库中的核心类,Jackson的消息转换器并不认识这个类型,所以无法将它正确序列化为HTTP响应中的JSON内容,导致抛出无法写入响应体的异常。

解决方法

这里有两种常用的处理方式:

1. 手动将JsonElement转为JSON字符串返回

修改你的Controller方法,用Gson把JsonElement直接序列化为字符串,Spring会自动把这个字符串作为JSON响应返回:

@GetMapping(path = "/device/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
String getDevicesConfigs(@PathVariable("id") String id) {
    JsonElement driverConfigParams = halBroker.getDriverConfigParams(id);
    return new Gson().toJson(driverConfigParams);
}

这种方式简单直接,不需要修改全局配置。

2. 配置Spring使用Gson作为默认JSON处理器

如果你的项目中大量使用Gson的类型,推荐全局配置Spring使用Gson消息转换器,这样就能直接返回JsonElement类型了:
创建一个配置类:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new GsonHttpMessageConverter());
        // 如果需要保留Jackson的转换器,可以不清除原有转换器,否则可以调用converters.clear()
    }
}

配置完成后,你的原始Controller代码就能正常工作,Spring会自动用Gson处理JsonElement的序列化。

内容的提问来源于stack exchange,提问作者m.bouali

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:48:03