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

SAP Hybris中ItemModel转JSON遇无限递归问题求解决方案

SAP Hybris ItemModel转JSON解决无限递归问题

你遇到的com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion是因为Hybris的ItemModel普遍存在双向关联(比如Product和Category互相持有引用),Jackson默认序列化时会不断遍历这些关联,导致无限递归。下面给你几种可行的解决办法:

方法1:用Hybris自带的JSON转换工具

Hybris内置了专门处理Model序列化的工具,能自动截断循环关联,避免递归问题:

import de.hybris.platform.servicelayer.dto.converter.Converter;
import de.hybris.platform.servicelayer.dto.converter.DefaultConverterRegistry;
import de.hybris.platform.servicelayer.model.ModelService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

// 注入所需服务
@Autowired
private ModelService modelService;
@Autowired
private DefaultConverterRegistry converterRegistry;

public String convertItemsToJson(List<ItemModel> itemModels) {
    if (itemModels.isEmpty()) {
        return "[]";
    }
    // 获取对应ItemType的JSON转换器
    Converter<ItemModel, Map<String, Object>> jsonConverter = converterRegistry.getConverter("json", itemModels.get(0).getClass());
    List<Map<String, Object>> dtoList = new ArrayList<>();
    
    for (ItemModel item : itemModels) {
        // 先刷新模型,确保加载所有必要属性(避免懒加载导致的序列化问题)
        modelService.refresh(item);
        dtoList.add(jsonConverter.convert(item));
    }
    
    // 把Map列表转成JSON字符串
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.writeValueAsString(dtoList);
    } catch (JsonProcessingException e) {
        throw new RuntimeException("JSON转换失败", e);
    }
}

方法2:配置Jackson忽略循环引用

如果想用原生Jackson序列化,可以通过注解或全局配置来阻断递归:

方式A:给自定义Model加注解

如果是你自己定义的ItemModel,在双向关联的字段上分别加@JsonManagedReference和@JsonBackReference:

public class ProductModel extends ItemModel {
    @JsonManagedReference // 主动引用方,正常序列化
    private List<CategoryModel> categories;
}

public class CategoryModel extends ItemModel {
    @JsonBackReference // 被动引用方,序列化时会被忽略
    private ProductModel product;
}

方式B:全局配置Jackson

在Spring配置里定义全局的ObjectMapper,自定义ItemModel的序列化逻辑,只输出你需要的属性:

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import de.hybris.platform.core.model.ItemModel;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

@Configuration
public class JacksonConfig {
    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        // 关闭自引用失败的校验
        mapper.configure(SerializationFeature.FAIL_ON_SELF_REFERENCES, false);
        
        // 自定义ItemModel的序列化器
        SimpleModule module = new SimpleModule();
        module.addSerializer(ItemModel.class, new JsonSerializer<ItemModel>() {
            @Override
            public void serialize(ItemModel value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                gen.writeStartObject();
                // 只序列化你需要的属性,比如PK、创建时间等
                gen.writeStringField("pk", value.getPk().getLongValueAsString());
                gen.writeStringField("creationTime", value.getCreationtime().toString());
                // 按需添加其他属性,例如商品名称:gen.writeStringField("name", ((ProductModel)value).getName());
                gen.writeEndObject();
            }
        });
        mapper.registerModule(module);
        
        return mapper;
    }
}

方法3:用DTO中转(最灵活)

创建对应ItemType的DTO类,只保留你需要的字段,先把ItemModel转成DTO,再序列化DTO:

import de.hybris.platform.core.model.product.ProductModel;
import de.hybris.platform.core.model.order.CartModel;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.ArrayList;
import java.util.List;

// 示例ProductDTO
class ProductDTO {
    private String pk;
    private String name;
    private String creationTime;

    public ProductDTO(ProductModel product) {
        this.pk = product.getPk().getLongValueAsString();
        this.name = product.getName();
        this.creationTime = product.getCreationtime().toString();
    }

    // getter方法(Jackson序列化需要)
    public String getPk() { return pk; }
    public String getName() { return name; }
    public String getCreationTime() { return creationTime; }
}

// 示例CartDTO
class CartDTO {
    private String pk;
    private String code;
    private String creationTime;

    public CartDTO(CartModel cart) {
        this.pk = cart.getPk().getLongValueAsString();
        this.code = cart.getCode();
        this.creationTime = cart.getCreationtime().toString();
    }

    // getter方法
    public String getPk() { return pk; }
    public String getCode() { return code; }
    public String getCreationTime() { return creationTime; }
}

// 转换方法
public String convertItemsToJson(List<ItemModel> itemModels) {
    List<Object> dtoList = new ArrayList<>();
    for (ItemModel item : itemModels) {
        if (item instanceof ProductModel) {
            dtoList.add(new ProductDTO((ProductModel) item));
        } else if (item instanceof CartModel) {
            dtoList.add(new CartDTO((CartModel) item));
        }
        // 其他ItemType同理,添加对应的DTO转换
    }

    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.writeValueAsString(dtoList);
    } catch (JsonProcessingException e) {
        throw new RuntimeException("JSON转换失败", e);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 01:55:58