سؤال

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.

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

Take a look at google Gson instead:

  • Apache license
  • No other dependancies
  • Simple usage

This is example:

import com.google.gson.Gson;

class Foo {
    private String hello;

    public String toString() {
        return "hello='" + hello + "'";
    }
}

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

        Gson gson = new Gson();
        Foo foo = gson.fromJson(text, Foo.class);

        System.out.println(foo.toString());
        System.out.println(gson.toJson(foo));
    }
}

And voila!

$ javac -cp lib/gson-2.0.jar hello.java
$ java -cp .:lib/gson-2.0.jar hello
hello='world'
{"hello":"world"}
$
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top