5

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
Sandeep Chatterjee
  • 3,220
  • 9
  • 31
  • 47
ivknv
  • 305
  • 1
  • 4
  • 14

3 Answers3

6

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    I tried to run code with classpath but I still get the same error – ivknv Jun 05 '14 at 16:48
  • 1
    @SPython: Well you've not told us the full error, which makes it harder to help you. Maybe there are more jar files you need. Please edit your question with more information. – Jon Skeet Jun 05 '14 at 16:51
1

If you are using an IDE, download the jar from this link.In netbeans and eclipse you can add this jar by right clicking on project then selecting properties->libraries->Add jar->Select the jar and click ok.

Balaji Dubey
  • 446
  • 5
  • 10
1

Did you compile your code with -cp json-simple-1.1.1.jar?

Sometime ago, I made a Test.java, and compiled with:

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

Then:

java -cp .:json-simple-1.1.1.jar Test

And It ran perfectly.

Paulo
  • 1,458
  • 2
  • 12
  • 26