您的位置:首页 > 移动开发 > Objective-C

JSONObject example in Java

2012-01-12 15:07 411 查看
n 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, youhave also studied how to parse and create messages with JSON in JavaScript. Nowin this part you will
study how to use JSON in Java.

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

commons-lang.jar 
commons-beanutils.jar
commons-collections.jar
commons-logging.jar
ezmorph.jar
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 forretransforming them back to beans, collections, maps and others.

In this example we are going to use JSONObjectclass for creating an object of
JSONObject and then we will print theseobject value. For using
JSONObject
class we have to import followingpackage "net.sf.json". To add elements in this object we haveused
put() method. Here is the full example code of
FirstJSONJava.java
isas 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 stepsas follows:

Download JSON-lib jar and other supporting Jars
Add these jars to your classpath
create and save FirstJSONJava.java
Compile it and execute ,You  will get following output:

Output:



 

Download Source Code

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息