Map to JSON
JSON Simple is a java library for encoding and decoding JSON text.
Get the latest binaries from
http://code.google.com/p/json-simple/ .
The following example shows converting a Map to JSON string.
package com.bethecoder.tutorials.json_simple.tests;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.json.simple.JSONValue;
public class Map2Json {
/**
* @param args
*/
public static void main ( String [] args ) {
Map<String, Object> map = new HashMap<String, Object> () ;
map.put ( "name" , "Sriram" ) ;
map.put ( "age" , 2 ) ;
map.put ( "dob" , new Date ( 110 , 4 , 6 )) ;
map.put ( "hobby" , "painting" ) ;
String jsonStr = JSONValue.toJSONString ( map ) ;
System.out.println ( jsonStr ) ;
}
}
It gives the following output,
{"dob":Thu May 06 00:00:00 IST 2010,"age":2,"name":"Sriram","hobby":"painting"}