简体   繁体   English

解码JSON,其中标签是值

[英]decoding JSON where tags are values

I have a JSON file that's formatted like this: 我有一个格式如下的JSON文件:

{
  "Cubs": {
    "city": "Chicago",
    "league": "National",
    "division": "Central"
  },
  "Cardinals": {
    "city": "St. Louis",
    "league": "National",
    "division": "Central"
  }
}

What I'd like to get out of parsing it is a Map<String,TeamInfo> where the key is the team name. 我想从解析中得到的是Map<String,TeamInfo> ,其中的关键是团队名称。

I'm trying to use Jackson to decode this - the structures of the information for the teams is pretty well defined, but the tags are the names of the teams. 我正在尝试使用杰克逊(Jackson)来解码-团队的信息结构定义得很好,但是标签是团队的名称。 I don't have control over the input format, this is what we use. 我无法控制输入格式,这就是我们使用的格式。

I've tried parsing it this way: 我试过这样解析:

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;
}

It parses just fine, but the resulting object is a Map of Maps rather than a Map of TeamInfo's. 它解析得很好,但是生成的对象是Maps Map,而不是TeamInfo Map。

结果

It feels close yet far away at the the same time. 同时感觉很近又很远。 Any thoughts on things to try? 对尝试的事情有任何想法吗?

Think this should work for you: 认为这应该为您工作:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM