Tuesday, March 11, 2014

Encoding JSON in Java with libjson-simple


Before start to encoding/decoding JSON using Java, we will need to install a JSON library. In this example I will use libjson-simple as follow:

pi@raspberrypi ~/$ sudo apt-get install libjson-simple-java

Once we have installed the library we need to update our CLASSPATH system variable:


pi@raspberrypi ~/$ export CLASSPATH=$CLASSPATH:/usr/share/java/json_simple-1.1.jar
Now we are ready to coding. Let use the next code:

import org.json.simple.JSONObject;

class JsonEncodeDemo
{
   public static void main(String[] args)
   {
      JSONObject obj = new JSONObject();

      obj.put("protocol", "mbus");
      obj.put("length", new Integer(168));
      obj.put("manufacturer", new Integer(4897));
      obj.put("valid", new Boolean(true));

      System.out.print(obj);
   }
}

To execute the code we can use:

pi@raspberrypi ~/java $ javac JsonEncodeDemo.java
pi@raspberrypi ~/$ java JsonEncodeDemo{"valid":true,"protocol":"mbus","manufacturer":4897,"length":168}

Hope help!!

No comments:

Post a Comment