在程序开发过程中,在参数传递,函数返回值等方面,越来越多的使用JSON。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,同时也易于机器解析和生成、易于理解、阅读和撰写,而且Json采用完全独立于语言的文本格式,这使得Json成为理想的数据交换语言。
JSON建构于两种结构:
“名称/值”对的集合(A Collection of name/value pairs),在不同的语言中,它被理解为对象(Object), 记录(record), 结构(struct), 字典(dictionary), 有趣列表(keyed list), 哈希表(hash table)或者关联数组(associative array)。
其实JSON数据就是一段字符串而已,只不过有不同意义的分隔符将其分割开来而已,我们看上面的符号,里面有[] ,{}等符号,其中
1 []中括号代表的是一个数组;
2 {}大括号代表的是一个对象
3 双引号“”表示的是属性值
4 冒号:代表的是前后之间的关系,冒号前面是属性的名称,后面是属性的值,这个值可以是基本数据类型,也可以是引用数据类型。
————————————————
使用net.sf.json需要导入的jar包
jar包下载:https://pan.baidu.com/s/1iZiXw55TPwIxYFQQCaR9Gw
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);
//根据key返回
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 = new JSONArray();
jsonArray.add(0, "张三");
jsonArray.add(1, "123");
//开始添加
json.element("student", jsonArray);
System.out.println(json);
}
}
运行结果: