Map to JSON
Google-gson is a java library from Google for encoding and decoding JSON text.
Get the latest binaries from
http://code.google.com/p/google-gson/ .
The following example shows converting a java map to JSON string.
package com.bethecoder.tutorials.google_gson.tests;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
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" ) ;
Gson gson = new GsonBuilder () .setPrettyPrinting () .create () ;
String jsonStr = gson.toJson ( map ) ;
System.out.println ( jsonStr ) ;
}
}
It gives the following output,
{
"dob": "May 6, 2010 12:00:00 AM",
"age": 2,
"name": "Sriram",
"hobby": "painting"
}