Example of creating simple JSON in JAVA

To know more about JSON , read “What is JSON and Understanding JSON syntax with simple example” and “Cloud Technologies”

In this post, we will show you how to create a simple JSON by writing code in JAVA,

$ vim simpleJsonObjectExample.java
import org.json.simple.JSONObject;

public class simpleJsonObjectExample {
        public static void main(String args[]) {
                JSONObject myObject = new JSONObject();
                myObject.put("myname", "lynxbee");
                myObject.put("myurl", "www.lynxbee.com");
                System.out.println("We created JSON as example : " + myObject);
        }
}

Here, the JSON object is created as,

JSONObject myObject = new JSONObject();

now, the JSON elements can be added to this object as,

myObject.put("myname", "lynxbee");

Compile this program using javac compiler in Ubuntu as,

$ javac simpleJsonObjectExample.java

Error we received when tried to compile this program on Ubuntu,

javac simpleJsonObjectExample.java 
simpleJsonObjectExample.java:1: error: package org.json.simple does not exist
import org.json.simple.JSONObject;

this error means, there is no JSON package is installed on your Ubuntu machine, so lets try and resolve this error…

$ sudo apt-get install libjson-simple-java

you can see this JSON library is installed as,

$ ls -alh /usr/share/java/json*
/usr/share/java/json-simple-2.3.0.jar -> json-simple.jar
/usr/share/java/json-simple.jar

Now we need to add this library to classpath as,

$ export CLASSPATH=$CLASSPATH:/usr/share/java/json-simple.jar
$ echo $CLASSPATH
:/usr/share/java/json-simple.jar

Now, lets again compile this program as,

$ javac simpleJsonObjectExample.java

Now, if we run the compiled JAVA program, we can see that we created simple JSON with only one object as below,

$ java simpleJsonObjectExample
We created JSON as example : {"myname":"lynxbee","myurl":"www.lynxbee.com"}

Leave a Comment