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

从C盘读取JSON转MusicPiece列表报错求助

解决Jackson反序列化MusicPiece对象的错误

问题原因分析

报错提示Cannot construct instance of com.Entities.MusicPiece(no Creators, like default constructor, exist),核心问题有两个:

  1. 缺少无参构造函数:Jackson默认需要通过无参构造函数创建对象实例,再通过setter注入属性,但你的MusicPiece类只有带参构造。
  2. 字段不匹配+类型冲突:JSON里的字段(title、author、duration)和实体类字段(music_title、interprete、duree)名称不对应;且JSON中duration是double类型,实体类duree是int类型,类型不兼容。

具体修复步骤

1. 添加无参构造函数

在MusicPiece类中补充无参构造,供Jackson实例化对象:

public MusicPiece() {
    // 无参构造,无需逻辑
}

2. 修正字段映射与类型匹配

使用@JsonProperty注解关联JSON字段和实体类字段,同时调整duree的类型匹配JSON中的数值类型:
修改后的MusicPiece核心代码:

import com.fasterxml.jackson.annotation.JsonProperty;

public class MusicPiece implements Comparator<MusicPiece>{
    @JsonProperty("title") // 映射JSON的title字段
    private String music_title;
    private String genre;
    @JsonProperty("author") // 映射JSON的author字段
    private String interprete;
    @JsonProperty("duration") // 映射JSON的duration字段
    private double duree; // 改为double类型匹配JSON的数值

    // 保留原带参构造(注意更新duree的参数类型)
    public MusicPiece(String music_title, String genre, String interprete, double duree) {
        this.music_title = music_title;
        this.genre = genre;
        this.interprete = interprete;
        this.duree = duree;
    }

    // 添加无参构造
    public MusicPiece() {}

    // 更新duree的getter/setter类型
    public double getDuree() {
        return duree;
    }

    public void setDuree(double duree) {
        this.duree = duree;
    }

    // 其他getter/setter、toString、compare方法保持不变...
}

3. 调整主函数打印逻辑(可选)

因为duree改为double类型,打印时可按需格式化:

System.out.printf("duree : %.2f%n", musicPiece.getDuree());

额外方案(无需修改类型)

如果不想把duree改成double,可以通过自定义setter转换数值:

@JsonProperty("duration")
private int duree;

@JsonSetter("duration")
public void setDuree(double duration) {
    // 将分钟转为整数秒,可根据需求调整转换逻辑
    this.duree = (int) Math.round(duration * 60);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 12:17:48