我有一个格式如下的JSON文件:
{
"Cubs": {
"city": "Chicago",
"league": "National",
"division": "Central"
},
"Cardinals": {
"city": "St. Louis",
"league": "National",
"division": "Central"
}
}
我想要解析它的是Map<String,TeamInfo>
,其中关键是团队名称。
我试图用杰克逊解码这个 - 团队信息的结构定义很好,但标签是团队的名字。我无法控制输入格式,这就是我们使用的。
我尝试过这样解析:
public static class TeamInfo {
private String city;
private String league;
private String division;
public TeamInfo() {
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getLeague() {
return league;
}
public void setLeague(String league) {
this.league = league;
}
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
}
public Map<String, TeamInfo> parseTeamInfo(String inputFile) {
Map<String, TeamInfo> teamInfo = null;
try {
teamInfo = m_objectMapper.readValue(inputFile, Map.class);
} catch (IOException e) {
e.printStackTrace();
}
return teamInfo;
}
它解析得很好,但结果对象是地图地图而不是TeamInfo的地图。
在同一时间感觉很近但很远。关于要尝试的事情的任何想法?
答案 0 :(得分:2)
认为这应该适合你:
public Map<String, TeamInfo> parseTeamInfo(String inputFile) {
Map<String, TeamInfo> teamInfo = null;
try {
TypeReference<HashMap<String,TeamInfo>> typeRef
= new TypeReference<HashMap<String,TeamInfo>>() {};
HashMap<String,TeamInfo> o = mapper.readValue(inputFile, typeRef);
} catch (IOException e) {
e.printStackTrace();
}
return teamInfo;
}