How to use JSON object in java?

Let us discuss how to use JSON object in java with the help of below example.

Steps:

1. Include JSON jar in classpath.
2. Create JSONObject object.
3. Add data to JSONObject.
3. Process the object.

Example:

JSONTest.java
package com.javawithease.business;
import net.sf.json.JSONObject;
/**
* This class show use JSON object in java.
* @author javawithease
*/

public class JSONTest {
public static void main(String args[]){
//Create JSON object
JSONObject obj = new JSONObject();
 
//Add data to JSON object.
obj.put("name", "Bharat");
obj.put("rollNo", "MCA/07/05");
obj.put("id", new Integer(50));
 
//Print JSON object.
System.out.print(obj);
}
}

Output:

{"name":"Bharat","rollNo":"MCA/07/05","id":50}

No comments: