To generate json format using java , you must need json jar.

You can find json jar and  maven  using

http://mvnrepository.com/artifact/org.json/json/20140107

Note: you must include this jar in your project.

You can get source code using

https://github.com/douglascrockford/JSON-java

It has many classes. First we will see JSONObject


import org.json.JSONObject;

public class GenerateJson {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  JSONObject json=new JSONObject();
  System.out.println(json.toString());
 }

}

Output:
{}

If you execute the above code , that will produce empty pair,because we didn't passed any key value pair.

Next we are going to see , how to create a json for customer class.

Create a Customer class with name and age as member variable and generate getters and setters.


public class Customer {
String name;
int age;
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;
}
}

Then create JSONObject and pass Customer object with values.


import org.json.JSONObject;

public class GenerateJson {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Customer cust=new Customer();
		cust.setName("raja");
		cust.setAge(22);
		JSONObject json=new JSONObject(cust);
		System.out.println(json.toString());
	}

}

output:
{"name":"raja","age":22}