这是因为Jackson对于 Array 类型反序列化时默认转换为 ArrayList 类型
如果需要转换为 Array 类型,你需要对 ObjectMapper 对象进行配置
如:
ObjectMapper mapper = new ObjectMapper();
// USE_JAVA_ARRAY_FOR_JSON_ARRAY JSON中的Array类型转换为Java中的Array类型,true为转换为Array类型,false转换为ArrayList类型(默认)
mapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
Map map = mapper.readValue("{\"arr\":[1,2]}", Map.class);
System.out.println(map.get("arr").getClass());// class [Ljava.lang.Object;
System.out.println(Arrays.toString((Object[]) map.get("arr")));// [1, 2]
对于 ObjectMapper 的其他配置参考 https://ketao1989.github.io/2...
如果是在Spring Boot项目,可以这样配置
@RestController
@SpringBootApplication
public class Application {
@RequestMapping(value = "/json")
public Map json(@RequestBody Map body) {
for (Map.Entry entry : body.entrySet()) {
System.out.println(entry.getKey() + "的value类型为:" + entry.getValue().getClass());
}
return body;
}
public static void main(String[] args) {
SpringApplication.run(Application .class, args);
}
@Configuration
class JacksonConfiguration {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
return objectMapper;
}
}
}