Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NoClassDefFoundError when trying to parse JSON with JSON simple

I use JSON simple to parse JSON and I get NoClassDefFoundError when trying to create JSONParser object.

import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
...
JSONParser parser = new JSONParser();

I compile program with command:

javac MyProgram.java -cp json-simple-1.1.1.jar

And it compiles fine. But when I execute program with this command:

java MyProgram

I get NoClassDefFoundError

What am I doing wrong?

EDIT:
Full error:

Exception in thread "main" java.lang.NoClassDefFoundError: org/json/simple/parser/JSONParser
        at getNotesFromNoter.sendPost(getNotesFromNoter.java:53)
        at getNotesFromNoter.main(getNotesFromNoter.java:14)
Caused by: java.lang.ClassNotFoundException: org.json.simple.parser.JSONParser
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        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)
        ... 2 more
like image 294
ivknv Avatar asked Mar 20 '23 10:03

ivknv


1 Answers

You're not including the Simple JSON jar file in your classpath when running. You want:

// Unix
java -cp .:json-simple-1.1.1.jar MyProgram

// Windows
java -cp .;json-simple-1.1.1.jar MyProgram

(The : or ; is the path separator for the relevant operating system.)

When you compile Java and specify a classpath, that's just telling the compiler about the classes to compile against - it doesn't include the library in the result of the compilation, so you still need to specify the classpath in order to run the code, too.

like image 106
Jon Skeet Avatar answered Apr 25 '23 09:04

Jon Skeet