Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/ObjectMapper" when using gradle

I am writing a simple test program to convert json into java objects using jackson 2.

My code is,

package test;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URL;

public class UseJson{

    public static void main(String[] args){

        ObjectMapper mapper = new ObjectMapper();
        try{
            SomeClass obj = mapper.readValue(new URL("http://someurl"), SomeClass.class);
        }
        catch(Exception ex){
            System.out.println(ex.toString());
        }
    }
}

And the build.gradle file is

repositories {
    mavenCentral()
}

apply plugin: 'java'

dependencies{
    compile('com.fasterxml.jackson.core:jackson-databind:2.8.6')
    compile('com.fasterxml.jackson.core:jackson-core:2.8.6')
    compile('com.fasterxml.jackson.core:jackson-annotations:2.8.6')
}

jar {
        manifest {
                attributes 'Main-Class': 'test.UseJson'
        }
}

But I am getting an exception when trying to execute the program

java -jar ./build/libs/JsonTest.jar
Exception in thread "main" java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/ObjectMapper
        at test.UseJson.main(UseJson.java:10)
Caused by: java.lang.ClassNotFoundException: com.fasterxml.jackson.databind.ObjectMapper
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 1 more

The related posts java.lang.ClassNotFoundException / NoClassDefFoundError for com/fasterxml/jackson/databind/ObjectMapper with Maven and Correct set of dependencies for using Jackson mapper don't solve the problem.


Edit: When I tried to compile the program manually using javac and the jar files of the dependencies, it worked. The issue must be with the gradle build file.

like image 926
Registered User Avatar asked Sep 20 '25 04:09

Registered User


1 Answers

You will need to pack your libraries with your app.

jar {
archiveName = 'Name.jar'

manifest {
    attributes 'Main-Class': 'Main',
            'Class-Path': configurations.runtime.files.collect { "lib/$it.name" }.join(' '),
            'Implementation-Version': project.version (if any)
}

from(configurations.compile.collect { it.isDirectory() ? it : zipTree(it) })
}

Other solution would be using Shadow jar plugin.

The most recommended solution is to use application plugin. Why ? it's supported, it's Gradle, it's used by most developers.

like image 108
LazerBanana Avatar answered Sep 21 '25 18:09

LazerBanana