为什么无法通过展开根节点来反序列化对象数组?
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\":\"[email protected]\"},{\"email\":\"[email protected]\"}]}";
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);
}
}
我一直在仔细阅读Jackson文档,这是我能弄清楚的,但是在运行它时,出现以下错误:
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]
我想在不创建包装器类的情况下完成此操作。虽然这是一个示例,但我不想仅为了解包根节点而创建不必要的包装器类。
最佳答案
创建一个ObjectReader来显式配置根名称:
@Test
public void testUnwrapping() throws IOException {
String json = "{\"customers\":[{\"email\":\"[email protected]\"},{\"email\":\"[email protected]\"}]}";
ObjectReader objectReader = mapper.reader(new TypeReference<List<Customer>>() {})
.withRootName("customers");
List<Customer> customers = objectReader.readValue(json);
assertThat(customers, contains(customer("[email protected]"), customer("[email protected]")));
}
(顺便说一句,这是杰克逊2.5版的,您有其他版本吗?我有DeserializationFeature而不是DeserializationConfig.Feature)
似乎通过以这种方式使用对象读取器,您不需要全局配置“展开根值”功能,也不需要使用
@JsonRootName
批注。还要注意,您可以直接请求
List<Customer>
而不是通过数组-给ObjectMapper.reader
的类型就像ObjectMapper.readValue
的第二个参数一样工作