1

I am trying a simple json java program (no maven or IDE). This is my java file:

import javax.json.*;
import javax.json.Json;
import javax.json.JsonObject; 
import javax.json.JsonObjectBuilder;
import javax.json.JsonWriter;

class JsonTest {

public static void main(String[] args){
  JsonObject obj = Json.createObjectBuilder()
  .add("name", "foo")
  .add("num", new Integer(100))
  .add("balance", new Double(1000.21))
  .add("is_vip", new Boolean(true)).build();

  System.out.print(obj);
}
}

In the same directory of this file, I have the jar file:

javax.json-1.0.jar

I don't get any error in compiling:

javac -classpath ./javax.json-1.0.jar JsonTest.java

But when I run the program I get the error:

Exception in thread "main" java.lang.NoClassDefFoundError: javax/json/Json
    at JsonTest.main(JsonTest.java:10)
Caused by: java.lang.ClassNotFoundException: javax.json.Json
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 1 more    

Why am I getting this error when there was no error in compilation. I already searched other questions with this error but unlike them I am not using any IDE or maven. Any help will be appreciated.

Bhavik
  • 346
  • 4
  • 11

1 Answers1

1

You are not running it with the JSON JAR file on the classpath.

Try this:

java -classpath .:./javax.json-1.0.jar JsonTest

Change : to ; on Windows ....

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Thank you that worked! Why do I have to include jar file while running too? – Bhavik Apr 02 '17 at 07:31
  • Answers: 1) Because the docs say so. 2) Because the the `javac` compiler doesn't embed the dependent JAR or its pathname into the ".class" file. 3) Because Java doesn't have a direct equivalent of C#'s application manifest files. – Stephen C Apr 02 '17 at 07:36