I am trying to write a simple Java program which writes JSON data to a file. I am compiling it with the JSON simple jar file but I am getting an error. Below is what I have done:
//JsonSimpleWriteExample.java
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.io.FileWriter;
import java.io.IOException;
public class JsonSimpleWriteExample {
public static void main(String[] args) {
JSONObject obj = new JSONObject();
obj.put("name", "mkyong.com");
obj.put("age", new Integer(100));
JSONArray list = new JSONArray();
list.add("msg 1");
list.add("msg 2");
list.add("msg 3");
obj.put("messages", list);
try (FileWriter file = new FileWriter("f:\\test.json")) {
file.write(obj.toJSONString());
file.flush();
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(obj);
}
}
To compile the above program in a terminal, I am doing:
javac -cp json-simple-1.1.1.jar JsonSimpleWriteExample.java
I downloaded the json-simple-1.1.1.jar
file from http://www.java2s.com/Code/Jar/j/json-simple.htm
I am getting the below error:
Note: JsonSimpleWriteExample.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
I am using MacOS. Can anybody help me figure out the issue.
When I try running my class file I get the below error:
$ java JsonSimpleWriteExample
Error that I got:
Exception in thread "main" java.lang.NoClassDefFoundError: org/json/simple/JSONObject
at JsonSimpleWriteExample.main(JsonSimpleWriteExample.java:11)
Caused by: java.lang.ClassNotFoundException: org.json.simple.JSONObject
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more