Jackson JSON map key as property of contained object

后端 未结 3 2031
别跟我提以往
别跟我提以往 2021-01-12 03:16

Given a structure like this:

{
  \"nameOfObject\": { \"score\": 100 },
  \"anotherObject\": { \"score\": 30 }
}

Is it possible to map this

3条回答
  •  不知归路
    2021-01-12 03:20

    Here's an improved version of @Buzz Moschetti's, it uses Jackson's ObjectMapper.convertValue() to handle parsing the properties

    ObjectMapper mapper = new ObjectMapper();
    
    Map data = mapper.readValue(inputstream, Map.class);
    
    Container c = new Container();
    
    for(Map.Entry entry : data.entrySet()) {
        String name = entry.getKey();
        ScoreKeeper sk = mapper.convertValue(entry.getValue(), ScoreKeeper.class);
        sk.name = name;
        c.scoreKeepers.put(name, sk);
    }
    

提交回复
热议问题