为什么我不能打开根节点并反序列化一个对象数组?

Mri*_*lla 0 java json jackson deserialization json-deserialization

为什么我无法通过展开根节点来反序列化对象数组?

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

import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonRootName;
import org.junit.Assert;
import org.junit.Test;

public class RootNodeTest extends Assert {

    @JsonRootName("customers")
    public static class Customer {
        public String email;
    }

    @Test
    public void testUnwrapping() throws IOException {
        String json = "{\"customers\":[{\"email\":\"hello@world.com\"},{\"email\":\"john.doe@example.com\"}]}";
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE, true);
        List<Customer> customers = Arrays.asList(mapper.readValue(json, Customer[].class));
        System.out.println(customers);
    }
}
Run Code Online (Sandbox Code Playgroud)

我一直在挖掘杰克逊的文档,这是我能想到的,但在运行它时,我收到以下错误:

A org.codehaus.jackson.map.JsonMappingException has been caught, Root name 'customers' does not match expected ('Customer[]') for type [array type, component type: [simple type, class tests.RootNodeTest$Customer]] at [Source: java.io.StringReader@49921538; line: 1, column: 2]
Run Code Online (Sandbox Code Playgroud)

我想在不创建包装类的情况下完成此任务.虽然这是一个示例,但我不想仅为展开根节点创建不必要的包装类.

ara*_*nid 7

创建ObjectReader以显式配置根名称:

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

(顺便说一句,这是与Jackson 2.5,你有不同的版本吗?我有DeserializationFeature而不是DeserializationConfig.Feature)

似乎通过以这种方式使用对象阅读器,您不需要全局配置"展开根值"功能,也不需要使用@JsonRootName注释.

另请注意,您可以直接请求List<Customer>而不是通过数组 - 给定的类型ObjectMapper.reader就像第二个参数一样工作ObjectMapper.readValue