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

SpringBoot返回含locationtech Geometry对象时JSON序列化嵌套溢出问题

问题解决:Spring REST返回JTS Geometry类型时无限嵌套导致序列化失败

问题现象

使用Spring REST接口返回包含Geometry类型的Product对象时,其他字段正常输出,但location字段出现无限嵌套的envelope结构,最终触发序列化报错:

Ignoring exception, response committed already: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Document nesting depth (1001) exceeds the maximum allowed (1000, from StreamWriteConstraints.getMaxNestingDepth())

从数据库读取对象时location字段正常(日志能打印出LineString),问题出在JSON序列化阶段。

无需自定义序列化的解决方案

1. 引入Jackson JTS序列化模块

在pom.xml中添加专门处理JTS Geometry类型的Jackson模块依赖,它能正确处理Geometry的序列化/反序列化,避免递归嵌套:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jts</artifactId>
    <!-- 版本与Spring Boot内置Jackson版本匹配,Spring Boot 3.4.2对应Jackson 2.17.x -->
    <version>2.17.2</version>
</dependency>

2. 移除实体类中多余的反序列化注解

删除Product实体location字段上的@JsonDeserialize(as = Geometry.class)注解,该注解会干扰Jackson JTS模块的自动处理逻辑。修改后的实体字段:

@Column(name="location", nullable=true)
private Geometry location;

3. (可选)手动注册JTS模块(若自动配置未生效)

如果引入依赖后问题仍存在,可添加Jackson配置类手动注册JTS模块:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jts.JtsModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JacksonGeoConfig {
    @Bean
    public ObjectMapper geoObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JtsModule());
        return mapper;
    }
}

问题根源

Jackson默认通过反射序列化JTS Geometry对象时,Geometry的envelope属性会反向引用回自身,形成无限递归调用,最终触发JSON嵌套深度超限的错误。jackson-datatype-jts模块提供了针对JTS几何类型的专用序列化器,会将Geometry对象序列化为标准GeoJSON格式,彻底避免递归问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 18:56:17