Search code examples
javajson-lib

Basic JSON-lib example


I'm trying to use JSON-lib, but I can't get it to run without NoClassDefFoundError. Here's the code:

import net.sf.json.*;

public class hello {
    public static void main(String[] args) {
        String settings = "{\"hello\": \"world\"}";

        JSONObject obj = (JSONObject)JSONSerializer.toJSON(settings);
        System.out.println(obj.toString());
    }
}

And the command to compile:

javac -cp lib/json-lib-2.4-jdk15.jar hello.java

And the command to run:

java -cp .:lib/json-lib-2.4-jdk15.jar:lib/commons-lang-2.4.jar hello

I have also tried it with commons-lang3.3, which gives me different errors. I think it might be a version thing.

How do I compile and run a simple example with this library?

If there's a better library without crazy dependencies, I would love to hear about it. I've tried Douglas Crockford's JSON-Java, but I had similar problems.

I would need something with a liberal license, like Apache 2, MIT or similar.


Solution

  • The answer you seek is right there in the POM file https://repository.sonatype.org/service/local/repositories/central-proxy/content/net/sf/json-lib/json-lib/2.4/json-lib-2.4.pom

    You need the following dependencies:

    commons-beanutils-1.8.0
    commons-collections-3.2.1
    commons-lang.2.5
    commons-logging-1.1.1
    ezmorph-1.0.6
    

    optional

    xom.1.1 (if serializing from/to XML)
    oro-2.0.8 (if using the jdk13 version of the library)
    

    The project's website (http://json-lib.sourceforge.net/) also lists these requirements.

    It's very likely that commons-lang-2.6 will work with json-lib 2.4 however I cannot guarantee the same for commons-lang-3.x.