Why can't I unwrap the root node and deserialize an array of objects?

前端 未结 3 1374
野的像风
野的像风 2021-01-07 15:20

Why am I not able to deserialize an array of objects by unwrapping the root node?

import java.io.IOException;
import java.util.Arrays;
import java.util.List         


        
3条回答
  •  一整个雨季
    2021-01-07 15:34

    Create an ObjectReader to configure the root name explicitly:

    @Test
    public void testUnwrapping() throws IOException {
        String json = "{\"customers\":[{\"email\":\"hello@world.com\"},{\"email\":\"john.doe@example.com\"}]}";
        ObjectReader objectReader = mapper.reader(new TypeReference>() {})
                                          .withRootName("customers");
        List customers = objectReader.readValue(json);
        assertThat(customers, contains(customer("hello@world.com"), customer("john.doe@example.com")));
    }
    

    (btw this is with Jackson 2.5, do you have a different version? I have DeserializationFeature rather than DeserializationConfig.Feature)

    It seems that by using an object reader in this fashion, you don't need to globally configure the "unwrap root value" feature, nor use the @JsonRootName annotation.

    Note also that you can directly request a List rather than going through an array- the type given to ObjectMapper.reader works just like the second parameter to ObjectMapper.readValue

提交回复
热议问题