Skip to content
Advertisement

java.lang.NoClassDefFoundError: javax/json/Json

I have a simple Java project where I would like to build a Json string. For this, I use javax.json:

import javax.json.Json;
import javax.json.JsonObjectBuilder;

public class MyClass {
    public void MyFunc() {
        JsonObjectBuilder myBuilder = Json.createObjectBuilder(); # this line will trigger the exception
        // And some other code
    }
}

The project is build with maven, and in the pom I have added these dependencies:

<dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>3.8.1</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>javax.json</groupId>
    <artifactId>javax.json-api</artifactId>
    <version>1.0</version>
  </dependency>
  <dependency>
      <groupId>org.glassfish</groupId>
      <artifactId>javax.json</artifactId>
      <version>1.0.4</version>
  </dependency>    
</dependencies>

Compilation is ok. When I execute the code using that command:

java -cp target/classes MyClass

The main is in MyClass. I get:

Exception in thread "main" java.lang.NoClassDefFoundError: javax/json/Json
[...]
Caused by: java.lang.ClassNotFoundException: javax.json.Json
        at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
        ... 6 more

on the call to Json.createObjectBuilder().

Symptom is the same if you run it in the targer folder like that:

java MyClass

I have checked in my ~/.m2/repository folder and i have javax/json/javax.json-api/1.0/javax.json-api-1.0.jar. When I unzip it, I can see the Json.class file.

What’s wrong ???

Advertisement

Answer

The classpath does not have the javax.json-api-1.0.jar. Run it like this:

java -cp target/classes:~/.m2/repository/javax/json/javax.json-api/1.0/javax.json-api-1.0.jar MyClass

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement