简体   繁体   中英

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?

在使用java运行时,您必须使用-classpath

java -classpath json.jar MyClassName

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM