使用 jackson 库时,报 java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/exc/InputCoercionException
及 java.lang.ClassNotFoundException: com.fasterxml.jackson.core.exc.InputCoercionException
。
异常栈信息
异常描述很明显表示缺乏相关 class 类,即缺少相关的库
Exception in thread "main" java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/exc/InputCoercionException
at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory.createMapDeserializer(BasicDeserializerFactory.java:1376)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer2(DeserializerCache.java:384)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer(DeserializerCache.java:349)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:264)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:244)
at com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:142)
at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationContext.java:476)
at com.fasterxml.jackson.databind.ObjectMapper._findRootDeserializer(ObjectMapper.java:4389)
at com.fasterxml.jackson.databind.ObjectMapper._convert(ObjectMapper.java:3915)
at com.fasterxml.jackson.databind.ObjectMapper.convertValue(ObjectMapper.java:3853)
at ...
at ...
Caused by: java.lang.ClassNotFoundException: com.fasterxml.jackson.core.exc.InputCoercionException
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
... 12 more
错误原因
可能开发者处于精简导入原则,只导入了 2.10.0 版本的 jackson-databind 库,有个奇怪的设计就是该版本的库,居然在 maven 依赖 2.9.6 版本的 jackson-core 库(难以理解),所以原因就是当只导入 jackson-databind 库时,对应的 jackson-core 版本不对导致,相关类不存在。
解决方法
显性指定 jackson-core 即可,以 maven 为例,在 pom.xml 里增加该库指定版本坐标即可,示例如下:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
</dependency>
<!-- 添加对应的 jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.10.0</version>
</dependency>