tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 JSON > JSON LIB > Map to JSON

Map to JSON 

JSON-lib is a java library for serializing and de-serializing java beans, maps, arrays and collections in JSON format. Get the latest binaries from sourceforge http://json-lib.sourceforge.net/. This requires the libraries ( json-lib-2.4-jdk15.jar, xom-1.2.7.jar, ezmorph.jar commons-lang.jar, commons-collections.jar, commons-beanutils-1.7.jar and commons-logging-1.1.1.jar) to be in classpath. The following example shows converting a Map to JSON Object.

File Name  :  
com/bethecoder/tutorials/json_lib/tests/Map2Json.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.json_lib.tests;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

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(11046));
    map.put("hobby""painting");
    
    JSONObject obj = (JSONObjectJSONSerializer.toJSON(map);
    System.out.println(obj.toString(2))//pretty print with indent
  }

}
   

It gives the following output,
{
  "dob":   {
    "date": 6,
    "day": 4,
    "hours": 0,
    "minutes": 0,
    "month": 4,
    "seconds": 0,
    "time": 1273084200000,
    "timezoneOffset": -330,
    "year": 110
  },
  "age": 2,
  "name": "Sriram",
  "hobby": "painting"
}



 
  


  
bl  br