ObjectMapper writeValueAsString()在写入String时更改键名

时间:2015-12-31 13:55:17

标签: java json jackson

我正在尝试将DTO转换为字符串以存储在数据库中。我在打电话:

ObjectMapper mapper = new ObjectMapper();
        TypeFactory factory = mapper.getTypeFactory();
        // type of key of response map
        JavaType stringType = factory.constructType(String.class);
        // type of value of response map
        JavaType listOfDtosType = factory.constructCollectionType(ArrayList.class, SummonerRankedInfoDTOEntry.class);
        // create type of map
        JavaType responseType = factory.constructMapType(HashMap.class, stringType, listOfDtosType);
        try {
            assert json != null;
            Map<String, List<SummonerRankedInfoDTOEntry>> response = new ObjectMapper().readValue(json, responseType);
            summonerRankedInfoDTO.setIntegerSummonerRankedInfoDTOEntryMap(response);
            logger.info("Json has been de-serialized" + summonerRankedInfoDTO.getIntegerSummonerRankedInfoDTOEntryMap());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return summonerRankedInfoDTO;

在我的DTO上:http://codebeautify.org/javaviewer/cb5e233b

注意字段:

LeagueDTOEntry {
      division = 'V ', isFreshBlood = false, isHotStreak = false, isInactive = false, isVeteran = false, leaguePoints = 0, losses = 32, miniSeries = null, playerOrTeamId = 'TEAM - 77 b4b970 - 5e e2 - 11e4 - 9 d98 - c81f66db96d8 ', playerOrTeamName = 'Team Invertebrate ', wins = 32
     }

isFreshBlood,isHotStreak,isInactive和isVeteran字段。

我调用上面的代码并记录它返回的字符串,即:https://jsonblob.com/56852fd6e4b01190df4650cd

上面的所有字段都丢失了&#34;是&#34;部分:freshBlood,hotStreak等等。

我可以发布我的DTO,但我已经找了很长时间,不知道为什么要改变他们的名字。我不认为我曾经没有&#34; is&#34;因为&#34;是&#34;取决于API调用返回的值。

感谢任何帮助,不确定如何使这个问题不那么混乱......

编辑:我的LeagueEntryDTO是:

private String division;

private boolean isFreshBlood;
private boolean isHotStreak;
private boolean isInactive;
private boolean isVeteran;

private int leaguePoints;

private MiniSeriesDTOEntry miniSeries;
private String playerOrTeamId;
private String playerOrTeamName;
private int wins;
private int losses;

@Override
public String toString() {
    return "LeagueDTOEntry{" +
            "division='" + division + '\'' +
            ", isFreshBlood=" + isFreshBlood +
            ", isHotStreak=" + isHotStreak +
            ", isInactive=" + isInactive +
            ", isVeteran=" + isVeteran +
            ", leaguePoints=" + leaguePoints +
            ", losses=" + losses +
            ", miniSeries=" + miniSeries +
            ", playerOrTeamId='" + playerOrTeamId + '\'' +
            ", playerOrTeamName='" + playerOrTeamName + '\'' +
            ", wins=" + wins +
            '}';
}

1 个答案:

答案 0 :(得分:1)

如果你真的想保留is前缀而不是遵守标准的JavaBean约定,请用(例如)

注释你的getter
@JsonProperty("isInactive")

此外,您的JSON逻辑太复杂了。你应该做的只是

Map<String, List<SummonerRankedInfoDTOEntry>> response = 
    new ObjectMapper().readValue(
        json, 
        new TypeReference<Map<String, List<SummonerRankedInfoDTOEntry>>>() {});