sriram
sriram

Reputation: 9032

Adding json jar to classpath java

I'm very new to Java world. I want to add the Json lib to compile my program. I downloaded the file from here.

When I tried to compile the program with

  javac -classpath json.jar MyClassName.java

I'm getting the error :

Note: JsonSimpleExample.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

And when I tried to run :

java MyClassName

I'm getting:

Exception in thread "main" java.lang.NoClassDefFoundError: org/json/simple/JSONObject
    at MyClassName.main(MyClassName.java:9)
Caused by: java.lang.ClassNotFoundException: org.json.simple.JSONObject
    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:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    ... 1 more

Where I'm making the mistake?

Upvotes: 2

Views: 7251

Answers (4)

thar45
thar45

Reputation: 3560

Reason to the error was ,the class was present during compile time and let's application to compile successfully and linked successfully but not available during run-time.

java -classpath json.jar MyClassName (or)

java -cp json.jar MyClassName

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 692043

You're making two mistakes:

  1. The message you get from the compiler is a note, and not a compilation error. Follow the instructions to get details
  2. You forget to set the classpath when running the app:

    java -classpath json.jar;. MyClassName
    

(assuming you're on windows, and you're in the directory containing MyClassName.class). If you're on Unix, replace the ; by a :.

Note that it's bad practice to put classes in the default, root package.

Upvotes: 2

Vikdor
Vikdor

Reputation: 24134

The first output is warning from the Java compiler about use of unchecked code (like raw collections). The class file would have been successfully generated.

If you want to fix these warnings, then you can compile with -Xlint command line switch and fix/suppress the unchecked/unsafe warnings.

Upvotes: 0

Dan D.
Dan D.

Reputation: 32391

You have to use the -classpath when running with java as well.

java -classpath json.jar MyClassName

Upvotes: 6

Related Questions