I have below build.gradle file in which I have included json-simple dependency:
apply plugin: 'java'
repositories {
mavenCentral()
}
dependencies {
testImplementation('org.junit.jupiter:junit-jupiter-api:5.4.2')
testRuntime('org.junit.jupiter:junit-jupiter-engine:5.4.2')
compile 'com.googlecode.json-simple:json-simple:1.1.1'
}
test {
useJUnitPlatform()
}
jar {
manifest {
attributes(
'Main-Class': 'src.main.java.demo.Hello'
)
}
}
I have below class which uses json-simple:
package src.main.java.demo;
import org.json.simple.parser.JSONParser;
import org.json.simple.JSONObject;
public class Hello{
public String hello(){
try{String jsonString="{\"first\":\"Hello\",\"second\":\"world\"}";
JSONParser jspa=new JSONParser();
JSONObject job=(JSONObject)jspa.parse(jsonString);
return (String)job.get("first"); }
catch(Exception e){
return "";
}
}
public static void main(String[] args)
{
System.out.println(new Hello().hello());
}
}
The project builds successfully but on running the created jar file of project, it says it cannot find JSONParser and JSONObject
. It means that these dependencies are not added at runtime. What should I do to add them to the classpath?
Thank You!
You should create a fat jar. Change your build gradle like this
jar {
manifest {
attributes "Main-Class": "src.main.java.demo.Hello"
}
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it)}
}
}
for older Gradle you should use this
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}