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

Spring Boot RestController返回JSON无属性名问题排查与解决

问题原因

第三方库的Candlestick类被JSON序列化器(Spring Boot默认使用Jackson)识别为数组类型,导致序列化时仅输出属性值而非键值对。常见触发场景包括:

  • 类实现了Iterable、Collection等集合接口,Jackson默认按数组处理
  • 类上标注了@JsonFormat(shape = JsonFormat.Shape.ARRAY)注解,强制采用数组形式序列化
  • 第三方库为该类定制了数组类型的序列化器
解决方法

方法一:自定义DTO转换(推荐)

创建自己的数据传输对象(DTO),将第三方Candlestick对象转换为DTO后返回,完全控制输出格式,不受第三方类变化影响:

// 自定义DTO类
import lombok.Data; // 也可以手动编写getter/setter方法

@Data
public class CandlestickDTO {
    private Long timestamp;
    private String open;
    private String high;
    private String low;
    private String close;
    private String volume;
    private Long closeTimestamp;
    private String quoteAssetVolume;
    private Integer numberOfTrades;
    private String takerBuyBaseAssetVolume;
    private String takerBuyQuoteAssetVolume;

    // 转换方法
    public static CandlestickDTO from(Candlestick candlestick) {
        CandlestickDTO dto = new CandlestickDTO();
        dto.setTimestamp(candlestick.getTimestamp());
        dto.setOpen(candlestick.getOpen());
        dto.setHigh(candlestick.getHigh());
        dto.setLow(candlestick.getLow());
        dto.setClose(candlestick.getClose());
        // 根据第三方类的getter方法补充其他属性赋值
        return dto;
    }
}

修改控制器代码:

import java.util.stream.Collectors;

@GetMapping("/{symbol}/{timeframe}")
public List<CandlestickDTO> getOHLCV(@PathVariable("symbol") String symbol,
        @PathVariable("timeframe") String timeframe) {
    return service.getOHLCV(symbol, IntervalConverter.fromString(timeframe))
            .stream()
            .map(CandlestickDTO::from)
            .collect(Collectors.toList());
}

方法二:配置Jackson强制对象序列化

通过Spring Boot的Jackson配置,强制将Candlestick类按对象形式序列化:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JacksonConfig {
    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        // 针对第三方Candlestick类强制使用对象序列化
        mapper.configOverride(Candlestick.class)
                .setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.OBJECT));
        return mapper;
    }
}

⚠️ 注意:这种方式依赖第三方类的内部结构,如果后续第三方库修改了Candlestick类的属性或序列化逻辑,可能引发异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 09:56:03