JSON ProgramsI( Encoding and Decoding in Java)
Encoding JSON in Java
Following is a simple example to encode a JSON object using Java JSONObject which is a subclass of java.util.HashMap. No ordering is provided. If you need the strict ordering of elements, use JSONValue.toJSONString ( map ) method with ordered map implementation such as java.util.LinkedHashMap.
import org.json.simple.JSONObject;
class JsonEncodeDemo {
public static void main(String[] args){
JSONObject obj = new JSONObject();
obj.put("name", "compsciflix");
obj.put("num", new Integer(100));
obj.put("balance", new Double(2000.58));
obj.put("is_vip", new Boolean(true));
System.out.print(obj);
}
}
On compiling and executing the above program the following result will be generated −
{"balance": 2000.58, "num":100, "is_vip":true, "name":"compsciflix"}
Following is another example that shows a JSON object streaming using Java JSONObject −
import org.json.simple.JSONObject;
class JsonEncodeDemo {
public static void main(String[] args){
JSONObject obj = new JSONObject();
obj.put("name","compsciflix");
obj.put("num",new Integer(100));
obj.put("balance",new Double(1000.1));
obj.put("is_vip",new Boolean(true));
StringWriter out = new StringWriter();
obj.writeJSONString(out);
String jsonText = out.toString();
System.out.print(jsonText);
}
}
On compiling and executing the above program, the following result is generated −
{"balance": 1000.1, "num":100, "is_vip":true, "name":"compsciflix"}
No comments: