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

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.

File Name  :  
com/bethecoder/tutorials/google_gson/tests/Map2Json.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
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(11046));
    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"
}


                    Print

   



Books Recommendation

 
 
bl  br