Thursday, 4 August 2011

How to create Json file with the Gson library

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class GsonTest {
 // I've changed this to map so you can pair the objects to the json name.

static String allToJSon(Map<String, Object> objectsToJson) {
  StringBuffer buffer = new StringBuffer();
  // buffer.append("{");
  // buffer.append("\"jsonData\"");
  // buffer.append(":");
  buffer.append("{");
  // Use the builder
  Gson gson = new GsonBuilder().create();
  for (Iterator<Entry<String, Object>> i = objectsToJson.entrySet()
    .iterator(); i.hasNext();) {
   Entry<String, Object> e = i.next();
   buffer.append("\"" + e.getKey() + "\"");
   buffer.append(":");
   buffer.append(gson.toJson(e.getValue()));
   // Checking this twice to avoid adding the comma when there are no
   // more elements
   if (i.hasNext()) {
    buffer.append(",");
   }
  }
  buffer.append("}");
  // buffer.append("}");
  return buffer.toString();
 }
 public static void main(String[] args) {
  // In this map we will put the json names and the objects to be
  // converted into json.
  Map<String, Object> objectMap = new HashMap<String, Object>();
  // Object 1, person
  NameId person = new NameId();
  person.setId("1");
  person.setName("raju");
  objectMap.put("person", person);
  // Object 2, address
  NameId address = new NameId();
  address.setId("3");
  address.setName("Some where some place, far far away");
  objectMap.put("address", address);
  // To Json
  String s = allToJSon(objectMap);
  System.out.println(s);
 }

No comments:

Post a Comment