Jackson JSON map key as property of contained object

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

Given a structure like this:

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

Is it possible to map this

3条回答
  •  -上瘾入骨i
    2021-01-12 03:38

    I am a firm believer in separating your POJOs from externalization. Read your JSON into a Map and then build you Container/ScoreKeeper objects like this (apols for any typos):

    mapper = new ObjectMapper();
    
    Map data = mapper.readValue(inputstream, Map.class);
    
    Container c = new Container();
    
    for(Map.Entry me : data.entrySet()) {
        String key = me.getKey();
        Map info = (Map) me.getValue();
    
        ScoreKeeper sk = new ScoreKeeper();
        sk.setName(key);
        Integer q = info.get("score");
        sk.setScore(q);
    
        c.put(key, sk);
    }
    

提交回复
热议问题