如何从 C: 驱动器上的路径将 Json 数据发送到要使用的对象列表

问题描述 投票:0回答:1

使用我的 json 到路径的代码

public static List<MusicPiece> jsonToListObject(String path) throws Exception {
        return new ObjectMapper().readValue(new FileInputStream(path), new TypeReference<List<MusicPiece>>() {});
    }

主要发送发送到列表的json数据的sysout

public static void main(String[] args) 抛出异常 {

    List<MusicPiece> articleList = jsonToListObject("c:/data/json/data_song.json");
    for (MusicPiece musicPiece : articleList) {
        System.out.println("title: " + musicPiece.getMusic_title());
        System.out.println("duree : " + musicPiece.getDuree());
        
    }
}

音乐作品班

public class MusicPiece implements Comparator<MusicPiece>{
private String music_title;
private String genre;
private String interprete;
private int duree; 


public MusicPiece(String music_title, String genre, String interprete, int duree) {
    this.music_title = music_title;
    this.genre = genre;
    this.interprete = interprete;
    this.duree = duree;
    
}


public String getMusic_title() {
    return music_title;
}


public void setMusic_title(String music_title) {
    this.music_title = music_title;
}


public String getGenre() {
    return genre;
}


public void setGenre(String genre) {
    this.genre = genre;
}


public String getInterprete() {
    return interprete;
}


public void setInterprete(String interprete) {
    this.interprete = interprete;
}


public int getDuree() {
    return duree;
}


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


@Override
public String toString() {
    return "MusicPiece [music_title=" + music_title + ", genre=" + genre + ", interprete=" + interprete + ", duree="+ duree + "]";
}


@Override
public int compare(MusicPiece o1, MusicPiece o2) {
    
    return 0;
}


**Json file with the mock data**

[{"id":1,"title":"Porter","author":"Horton Twydell","喜欢":false,"duration":3.04}, {"id":2,"title":"美国灰","author":"Kenton Kamall","liked":false,"duration":4.1}, {"id":3,"title":"Dovetail","author":"Juieta Meedendorpe","喜欢":false,"duration":4.66}]

java json list objectmapper
1个回答
0
投票

您共享的 JSON 没有与您的 Music 类匹配的字段,因此无法解析。

如果您希望字段的设置与文件中存在的不同,则必须向每个字段添加

@JsonProperty("field name in json")
注释

© www.soinside.com 2019 - 2024. All rights reserved.