Home Tutorials Json JSONObject example in Java
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

JSONObject example in Java

Advertisement
In the previous section of JSON tutorials you have seen how JSON can be used with JavaScript to create objects and arrays, you have also studied how to parse and create messages with JSON in JavaScript.

JSONObject example in Java

     

In the previous section of JSON tutorials you  have seen how JSON can be used with JavaScript to create objects and arrays, you have also studied how to parse and create messages with JSON in JavaScript. Now in this part you will study how to use JSON in Java.

To have functionality of JSON in java you must have JSON-lib. JSON-lib also requires following "JAR" files:

  1. commons-lang.jar 
  2. commons-beanutils.jar
  3. commons-collections.jar
  4. commons-logging.jar
  5. ezmorph.jar
  6. json-lib-2.2.2-jdk15.jar

JSON-lib is a java library for that transforms beans, collections, maps, java arrays and XML to JSON and then for retransforming them back to beans, collections, maps and others.

In this example we are going to use JSONObject class for creating an object of JSONObject and then we will print these object value. For using JSONObject class we have to import following package "net.sf.json". To add elements in this object we have used put() method. Here is the full example code of FirstJSONJava.java is as follows:

FirstJSONJava.java

import net.sf.json.JSONObject;

public class FirstJSONJava
{
  public static void main(String args[]){
  JSONObject object=new JSONObject();
 object.put("name","Amit Kumar");
 object.put("Max.Marks",new Integer(100));
 object.put("Min.Marks",new Double(40));
 object.put("Scored",new Double(66.67));
 object.put("nickname","Amit");
 System.out.println(object);
  }
}  

 
To run this example you have to follow these few steps as follows:

Output:

 
Download Source Code
 

     

Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 27, 2008

Ask Questions?    Discuss: JSONObject example in Java   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
Moonlight
August 29, 2012
Retrieve JSON and decode it

What is given is really useful. But how about if I want to retrieve and decode JSON object??
deepak
September 3, 2012
JSON

good place to learn new technologies
DMCA.com