JSONThe following code example shows how to create a JSON output for an object using a simple StringBuffer Implementation. This snippet is just demonstrate how JSON data structure is assembled and to help understand JSON better. For real world it is preferable to use standard JSON implementation available unless there is a compelling reason to roll out your own implementation. The snippet shows how a Customer object that has various attributes can be programatically represent in JSON. The xml and JSON representation of this entity customer can be. <customer> <name>Mr A</name> <age><33/age> <country>USA</country> <tel>11111111</tel> <tel>99999999</tel> </customer> Here name, age and country are represented as Name Value Pairs and tel is an Array of one or more than one telephone the customer has. This same information can be represented in JSON format as: {"customer":{ "name":"Mr A", "age":"33", "country":"USA", "tel":["111111111","9999999999"] }}

Snippet to create JSON data structure using StringBuffer

package com.livrona.snippets.json;

/**
 * This snippet simply uses StringBuffer to create a JSON data structure.
 * 
 * @author java4learners
 * 
 */
public class JSONGenerator {

	private StringBuffer buf = new StringBuffer();
	public static final String CURL_BEGIN = "{";
	public static final String CURL_END = "}";
	public static final String SQUARE_BEGIN = "[";
	public static final String SQUARE_END = "]";
	public static final String COLON = ":";
	public static final String COMMA = ",";
	public static final String QUOTES = """;
	public static final String NEW_LINE = "n";
	private int pairCount = 0;

	/**
	 * Begin the JSON Doc
	 * 
	 * @param value
	 */
	public void beginDoc(String value) {
		buf.append(CURL_BEGIN).append(QUOTES).append(value).append(QUOTES);
	}

	/**
	 * Add Object Attribute
	 * @param key
	 * @param value
	 */
	public void addPair(String key, String value) {
		if (pairCount > 0) {
			buf.append(COMMA).append(NEW_LINE);
		} else {
			buf.append(COLON).append(CURL_BEGIN).append(NEW_LINE);
		}
		buf.append(QUOTES).append(key).append(QUOTES).append(COLON).append(
				QUOTES).append(value).append(QUOTES);
		pairCount++;

	}

	/**
	 * Add array to the JSON doc
	 * 
	 * @param name
	 * @param values
	 */
	public void addArray(String name, String values[]) {
		StringBuffer ar = new StringBuffer();
		for (int i = 0; i < values.length; i++) {
			// append comma
			if (i > 0) {
				ar.append(COMMA);
			}
			ar.append(QUOTES).append(values[i]).append(QUOTES);
		}

		if (pairCount > 0) {
			buf.append(COMMA).append(NEW_LINE);
		} else {
			buf.append(COLON).append(CURL_BEGIN).append(NEW_LINE);
		}

		// add it as pair
		buf.append(QUOTES).append(name).append(QUOTES).append(COLON);
		buf.append(SQUARE_BEGIN);
		buf.append(ar.toString());
		buf.append(SQUARE_END);
	}

	/**
	 * End JSON doc
	 */
	public void endDoc() {
		buf.append(NEW_LINE);
		if (pairCount > 0) {
			buf.append(CURL_END);
		}
		buf.append(CURL_END);
	}

	public String toJSON() {
		return buf.toString();
	}
}

/**
 * Test Class
 * @author java4learners
 *
 */
class JSONGeneratorTest {

	public static void main(String[] args) throws Exception {
		JSONGenerator doc = new JSONGenerator();

		// populate a customer
		Customer cust = new Customer();
		cust.setName("Mr A");
		cust.setAge(33);
		cust.setCountry("USA");
		String tels[] = { "111111111", "9999999999" };
		cust.setTelephones(tels);

		// Add elements to the doc
		doc.beginDoc("customer");
		doc.addPair("name", cust.getName());
		doc.addPair("age", "" + cust.getAge());
		doc.addPair("country", cust.getCountry());
		doc.addArray("tel", cust.getTelephones());
		doc.endDoc();

		System.out.println("JSON struct :n" + doc.toJSON());
	}
}

/**
 * Customer, a sample data structure to be serialized
 * 
 * @author java4learners
 * 
 */
class Customer {
	private String name;
	private int age;
	private String country;
	private String telephones[];

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	public String[] getTelephones() {
		return telephones;
	}

	public void setTelephones(String[] telephones) {
		this.telephones = telephones;
	}

}