如何正确的使用JSONObject

  介绍

本篇文章给大家分享的是有关如何正确的使用JSONObject,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

JSONObject只是一种数据结构,可以理解为JSON格式的数据结构(键值结构),可以使用把方法给JSON对象添加元素.JSONObject可以很方便的转换成字符串,也可以很方便的把其他对象转换成JSONObject对象。

简介

在程序开发过程中,在参数传递,函数返回值等方面,越来越多的使用JSON.JSON (JavaScript对象表示法)是一种轻量级的数据交换格式,同时也易于机器解析和生成,易于理解,阅读和撰写,而且JSON采用完全独立于语言的文本格式,这使得JSON成为理想的数据交换语言只
JSON建构于两种结构:

"名称/值”对的集合(名称/值对的集合),在不同的语言中,它被理解为对象(对象),记录(记录),结构(结构),字典(字典),有趣列表(键列表),哈希表(哈希表)或者关联数组(关联数组)。

<强> JSONObject依赖:

最后一行需要保留,有两个jdk版本的实现:JSON -自由- 2.1 - jdk13.jar和JSON -自由- 2.1 jdk15。jar

& lt; dependency>   ,& lt; groupId> net.sf.json-lib   ,& lt; artifactId> json-lib   ,& lt; version> 2.4 & lt;/version>   ,& lt; classifier> jdk15   & lt;/dependency>

<强>使用net.sf。json需要导入的jar包

如何正确的使用JSONObject

jar包下载:

链接:https://pan.baidu.com/s/1nxwl-R3n6hNVMepT8LWNmw

提取码:p8w8

JSONObject

创建JSONObject,添加属性

//创建JSONObject   JSONObject  json =, new  JSONObject ();//添加属性   json.put (“username",,“张三“);   json.put (“password",,“123“);//打印   System.out.println (json);   ,//增加属性   json.element (“sex",,“男”);   json.put (“age",, 18);   System.out.println (json);

根据关键返回输出

System.out.println (json.get (“sex"));

判断输出对象的类型

boolean  isArray =, json.isArray ();   boolean  isEmpty =, json.isEmpty ();   boolean  isNullObject =, json.isNullObject ();   System.out.println(“是否数组:“+ isArray +“,,是否空:“+ isEmpty +“,,是否空为空对象:“+ isNullObject);

把JSONArray添加到JSONObject中

/JSONArray把添加到JSONObject中   JSONArray JSONArray  JSONArray =, new  ();   jsonArray.add(0,,“张三“);   jsonArray.add (1,“123“);//开始添加   jsonArray json.element (“student",,);   System.out.println (json);

全部代码:

import  net.sf.json.JSONArray;   import  net.sf.json.JSONObject;   ,   public  class  Json  {   public  static  void  main (String [], args), {//创建JSONObject   JSONObject  json =, new  JSONObject ();//添加属性   json.put (“username",,“张三“);   json.put (“password",,“123“);//打印   System.out.println (json);//增加属性   json.element (“sex",,“男”);   json.put (“age",, 18);   System.out.println (json);//根据关键返回   System.out.println (json.get (“sex"));//判断输出对象的类型   boolean  isArray =, json.isArray ();   boolean  isEmpty =, json.isEmpty ();   boolean  isNullObject =, json.isNullObject ();   System.out.println(“是否数组:“+ isArray +“,,是否空:“+ isEmpty +“,,是否空为空对象:“+ isNullObject);      System.out.println (“=====?;//把JSONArray添加到JSONObject中   JSONArray JSONArray  JSONArray =, new  ();   jsonArray.add(0,,“张三“);   jsonArray.add (1,“123“);//开始添加   jsonArray json.element (“student",,);   System.out.println (json);   }   }

运行结果:

如何正确的使用JSONObject

JSONArray

创JSONArray建,添加属性值

//创JSONArray建   JSONArray JSONArray  JSONArray =, new  ();//添加   jsonArray.add(0,,“张三“);   jsonArray.add (1,“123“);   jsonArray.element(“男“);   系统。

根据下标返回输出

System.out.println (jsonArray.get (0));

如何正确的使用JSONObject