Jackson JSON map key as property of contained object

后端 未结 3 2030
别跟我提以往
别跟我提以往 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:40

    Alternative solution, where the key name is set on the value object by using a custom Deserializer:

    @Test
    public void test() throws JsonParseException, JsonMappingException, IOException {
        ObjectMapper mapper = new ObjectMapper();
    
        Data data = mapper.readValue("{\"users\": {\"John\": {\"id\": 20}, \"Pete\": {\"id\": 30}}}", Data.class);
    
        assertEquals(20, data.users.get("John").id);
        assertEquals(30, data.users.get("Pete").id);
        assertEquals("John", data.users.get("John").name);
        assertEquals("Pete", data.users.get("Pete").name);
    }
    
    public static class Data {
        @JsonDeserialize(contentUsing = Deser.class)
        public Map users;
    }
    
    public static class User {
        public String name;
        public int id;
    }
    
    public static class Deser extends JsonDeserializer {
    
        @Override
        public User deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            String name = ctxt.getParser().getCurrentName();
    
            User user = p.readValueAs(User.class);
    
            user.name = name;  // This copies the key name to the value object
    
            return user;
        }
    }
    

提交回复
热议问题