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

Spring Boot 2.7.5集成Spring Hateoas 1.x与Gson序列化异常求助

解决Spring Hateoas 1.x与Gson的序列化兼容问题

一、修复Gson对RepresentationModel的序列化适配

Spring Hateoas 1.x的RepresentationModel包含Link集合,Gson默认无法正确处理其内部类型信息,你可以尝试以下自定义TypeAdapter的正确实现方式:

  1. 编写针对RepresentationModel的通用TypeAdapter
import com.google.gson.*;
import org.springframework.hateoas.RepresentationModel;
import java.lang.reflect.Type;

public class RepresentationModelTypeAdapter<T extends RepresentationModel<T>> implements JsonSerializer<T> {
    @Override
    public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context) {
        JsonObject jsonObject = new JsonObject();
        // 序列化实体自身字段
        jsonObject.add("content", context.serialize(src, typeOfSrc.getRawType()));
        // 序列化links集合
        jsonObject.add("_links", context.serialize(src.getLinks()));
        return jsonObject;
    }
}
  1. 将TypeAdapter注册到Gson实例
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.hateoas.RepresentationModel;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class GsonConfig {
    @Bean
    public Gson gson() {
        return new GsonBuilder()
                .registerTypeHierarchyAdapter(RepresentationModel.class, new RepresentationModelTypeAdapter<>())
                .create();
    }
}

注意:如果你的实体包含特殊类型字段,需要额外添加对应TypeAdapter确保序列化正常。

二、使用Spring Hateoas官方Gson适配模块

Spring Hateoas 1.x提供了官方Gson适配模块,可直接引入配置:

  1. 添加依赖(若未自动引入)
<dependency>
    <groupId>org.springframework.hateoas</groupId>
    <artifactId>spring-hateoas-gson</artifactId>
    <version>1.4.0</version> <!-- 与Spring Boot 2.7.5兼容的版本 -->
</dependency>
  1. 配置Gson时注册适配模块
import com.google.gson.Gson;
import org.springframework.hateoas.mediatype.hal.GsonHalModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class GsonConfig {
    @Bean
    public Gson gson() {
        return new GsonBuilder()
                .registerModule(new GsonHalModule())
                .create();
    }
}

该模块专门处理HAL格式的序列化逻辑,能正确解析RepresentationModel中的links集合。

三、替代框架方案

若上述方法无效,可考虑以下替代方案:

  • Spring Data Rest:自带Hateoas支持,对Gson兼容性更好,无需手动处理序列化;
  • JAX-RS Link规范:基于Jersey等JAX-RS实现,通过Link注解手动添加链接,配合Gson序列化更灵活;
  • 自定义链接逻辑:放弃Hateoas框架,在实体类中手动添加List<Link>字段,自行控制序列化逻辑,可控性更高但实现繁琐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 12:05:21