加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

JSONObject example in Java

发布时间:2020-12-16 19:28:05 所属栏目:百科 来源:网络整理
导读: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 prev
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 youhave 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:

  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 forretransforming them back to beans,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

importnet.sf.json.JSONObject;

publicclassFirstJSONJava
{
publicstaticvoidmain(Stringargs[]){
JSONObjectobject=newJSONObject();
object.put("name","AmitKumar");
object.put("Max.Marks",newInteger(100));
object.put("Min.Marks",newDouble(40));
object.put("Scored",newDouble(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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读