JSON是当前行业内使用最广泛的一种数据传输格式,是所有开发人员必备的技能之一。
选择Json,可以作为一种数据返回格式,也可以作为一种数据存储格式。
总结:JSON是行业内使用最为广泛的数据传输格式
Json (JavaScript Object Notation),是一种与开发语言无关的、轻量级的数据格式,更确切的是,它是一种数据格式或规范,对人来说具有易读、易编写的性质,对于机器来说易于程序解析与生成。
JSON数据演示:
{ "name": "pangPengCheng", "author": "庞鹏程", "content": [ "JSON笔记A", "JSON笔记B" ], "time": { "value": 30, "unit": "分钟" }, "major": ["计算机", "挖掘机"], "hobbys": { "hobby1": ["蓝球", "羽毛球", "健身"], "hobby2": [{ "food1": "烧烤" }, { "food2": "火锅" }] } }
1.JSON数值 { “key” : value}
{
"key" : 520,
"key1" : 1314
}
2.JSON字符串 { “key” : “value”}
{
"key": "五二零",
"key1": "一生一世"
}
3.JSON数组 { “key” : [value]}
{
"key" : [520, 1314],
"key1" : [520, 3344]
}
4.JSON对象 { “key” : {value}}
{
"key" : {"520": "我爱你"},
"key1" : {"1314": "一生一世"}
}
5.JSON对象数组 { “key” : [{“key1”: “value1”},{“key2”: “value2”}]}
{
"pangGe": [{
"hobby1": "蓝球"
},
{
"hobby2": "健身"
}
]
}
6.JSON数组对象 {“key”:{“key1”:[value1,value2]}}
{
"hobbys": {
"hobbys1": [2001612, 2002117],
"hobbys2": ["蓝球", "健身"]
}
}
JSON数据结构为:Object,Array
JSON基本数据类型为:String,number,true,false,null
Object:使用{}包含键值对结构,key必须是String类型(一定得使用“”),value值为其他任何基本类型或者数据结构。
Array:数组使用中括号[]来表示,使用逗号来分割元素
导入Pom依赖
org.json
json
20090211
package org.example.json;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
/**
* {
* "birthday": "2001-06-12",
* "major": ["篮球", "健身"],
* "school": "社会大学",
* "car": "java.lang.Object@7ea987ac",
* "name": "pangGe",
* "has_girlfriend": false,
* "comment": "这是一个注释",
* "house": ["兴文", "成都", "中心"],
* "age": 25.2,
* "food": {
* "food1": "烧烤",
* "food2": "火锅"
* }
* }
* */
public class RealizeJson {
public static void main(String[] args) throws JSONException {
jSONObjectSample();
}
private static void jSONObjectSample(){
JSONObject jsonObject = new JSONObject();
Object carObject = new Object();
System.out.println(carObject.toString()); //java.lang.Object@7ea987ac
HashMap foodHashMap = new HashMap<>();
foodHashMap.put("food1", "烧烤");
foodHashMap.put("food2", "火锅");
System.out.println(foodHashMap); //{food1=烧烤, food2=火锅}
JSONObject jsonFoodHashMap = new JSONObject(foodHashMap);
System.out.println(jsonFoodHashMap); //{"food1":"烧烤","food2":"火锅"}
String[] housesArrays=new String[]{"兴文","成都","中心"};
try {
jsonObject.put("name", "pangGe");
jsonObject.put("age", 25.2);
jsonObject.put("birthday", "2001-06-12");
jsonObject.put("school", "社会大学");
jsonObject.put("major", new String[] {"篮球","健身"});
jsonObject.put("has_girlfriend", false);
jsonObject.put("car", carObject);
jsonObject.put("house", housesArrays);
jsonObject.put("food",jsonFoodHashMap);
jsonObject.put("comment", "这是一个注释");
System.out.println(jsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Demo1上述案例结果:
{
"birthday": "2001-06-12",
"major": ["篮球", "健身"],
"school": "社会大学",
"car": "java.lang.Object@7ea987ac",
"name": "pangGe",
"has_girlfriend": false,
"comment": "这是一个注释",
"house": ["兴文", "成都", "中心"],
"age": 25.2,
"food": {
"food1": "烧烤",
"food2": "火锅"
}
}
//使用Map 构建JSON
private static void createJsonByMap() {
Map mapJson = new HashMap();
Object carObjectByMap = new Object();
System.out.println(carObjectByMap.toString()); //java.lang.Object@7ea987ac
HashMap foodHashMap = new HashMap<>();
foodHashMap.put("food1", "烧烤");
foodHashMap.put("food2", "火锅");
System.out.println(foodHashMap); //{food1=烧烤, food2=火锅}
JSONObject jsonFoodHashMap = new JSONObject(foodHashMap);
System.out.println(jsonFoodHashMap); //{"food1":"烧烤","food2":"火锅"}
String[] housesArrays=new String[]{"兴文","成都","中心"};
mapJson.put("name", "pangGe");
mapJson.put("age", 25.2);
mapJson.put("birthday", "2001-06-12");
mapJson.put("school", "社会大学");
mapJson.put("major", new String[] {"篮球","健身"});
mapJson.put("has_girlfriend", false);
mapJson.put("car", carObjectByMap);
mapJson.put("house", housesArrays);
mapJson.put("food",jsonFoodHashMap);
mapJson.put("comment", "这是一个注释");
System.out.println(mapJson); //{birthday=2001-06-12, major=[Ljava.lang.String;@610455d6, school=社会大学, car=java.lang.Object@61bbe9ba, name=pangGe, has_girlfriend=false, comment=这是一个注释, house=[Ljava.lang.String;@511d50c0, age=25.2, food={"food1":"烧烤","food2":"火锅"}}
System.out.println(new JSONObject(mapJson).toString()); //new JSONObject(Map map)
}
Demo2上述案例结果:
mapJson //mspJson不是一个JSON
{birthday=2001-06-12, major=[Ljava.lang.String;@610455d6, school=社会大学, car=java.lang.Object@61bbe9ba, name=pangGe, has_girlfriend=false, comment=这是一个注释, house=[Ljava.lang.String;@511d50c0, age=25.2, food={"food1":"烧烤","food2":"火锅"}}
new JSONObject(mapJSON) //new JSONObject(mapJSON) 是一个json
{
"birthday": "2001-06-12",
"major": ["篮球", "健身"],
"school": "社会大学",
"car": "java.lang.Object@61bbe9ba",
"name": "pangGe",
"has_girlfriend": false,
"comment": "这是一个注释",
"house": ["兴文", "成都", "中心"],
"age": 25.2,
"food": {
"food1": "烧烤",
"food2": "火锅"
}
}
注意!通过JavaBean来构建JSON数据时出现 "属性名":[{"bytes":[{},{},{},{},{},{}],"empty":false},{"bytes":[{},{},{},{},{},{},{},{},{}],"empty":false}] 这是因为导入的json jar包太老了,故此我们需要修改pom,把引入的JSON依赖版本提高
org.json
json
20160810
package org.example.json;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Map;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class PersonInfo {
private String name;
private String school;
private boolean has_girlfriend;
private double age;
private Object car;
private Object house;
private String[] major;
private String comment;
private String birthday;
private String[] hobby;
private Map foodsMap;
}
package org.example.json;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class RealizeJsonByJavaBean {
public static void main(String[] args) {
createJsonByJavaBean();
}
private static void createJsonByJavaBean() {
String[] hobbyArray = new String[]{"篮球","健身","羽毛球"};
System.out.println(hobbyArray);//[Ljava.lang.String;@677327b6
Map foodsHashMap = new HashMap();
foodsHashMap.put("food1", "烧烤");
foodsHashMap.put("food2", "火锅");
System.out.println(foodsHashMap);//{food1=烧烤, food2=火锅}
JSONObject hashMapToJson = new JSONObject(foodsHashMap);
System.out.println(hashMapToJson);//{"food1":"烧烤","food2":"火锅"}
PersonInfo jsonByJvaBean = new PersonInfo();
jsonByJvaBean.setName("pangGe");
jsonByJvaBean.setAge(22);
jsonByJvaBean.setBirthday("2001-06-12");
jsonByJvaBean.setSchool("社会大学");
jsonByJvaBean.setMajor(new String[] { "后端程序员", "前端程序员" });
jsonByJvaBean.setHas_girlfriend(false);
jsonByJvaBean.setCar(null);
jsonByJvaBean.setHouse(null);
jsonByJvaBean.setComment("JavaBean构建的JSON");
jsonByJvaBean.setHobby(hobbyArray);
jsonByJvaBean.setFoodsMap(foodsHashMap);
System.out.println(new JSONObject(jsonByJvaBean));
}
}
Demo3上述案例结果:
{
"birthday": "2001-06-12",
"major": ["后端程序员", "前端程序员"],
"school": "社会大学",
"name": "pangGe",
"has_girlfriend": false,
"comment": "JavaBean构建的JSON",
"foodsMap": {
"food1": "烧烤",
"food2": "火锅"
},
"age": 22,
"hobby": ["篮球", "健身", "羽毛球"]
}
在这里我们把JSON文件放在了resources目录下了
pangGeInfo.json数据:
{
"birthday": "2001-06-12",
"major": ["后端程序员", "前端程序员"],
"school": "社会大学",
"name": "pangGe",
"has_girlfriend": false,
"comment": "JavaBean构建的JSON",
"foodsMap": {
"food1": "烧烤",
"food2": "火锅"
},
"age": 22,
"hobby": ["篮球", "健身", "羽毛球"]
}
在这里我们使用到了 FileUtils工具类用来简化文件的相关操作,这个FileUtils工具类来自我们的依赖包commons-io,故此我们需要去pom里面添加依赖
commons-io
commons-io
2.4
package org.example.readjson;
import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
public class ReadJSONSFileInfo {
public static void main(String[] args) throws IOException, JSONException {
//构建的JSON文件在resources目录下,在resources目录下直接用/表示
File file = new File(ReadJSONSFileInfo.class.getResource("/pangGeInfo.json").getFile());
String content = FileUtils.readFileToString(file);
JSONObject jsonObject = new JSONObject(content);
System.out.println("姓名是:"+jsonObject.getString("name"));//姓名是:pangGe
System.out.println("年龄:"+jsonObject.getDouble("age")+"岁");//年龄:22.0岁
System.out.println("有没有女朋友?"+jsonObject.getBoolean("has_girlfriend"));//有没有女朋友?false
JSONArray majorArray = jsonObject.getJSONArray("major");
for(int i = 0;i < majorArray.length(); i++) {
String m = (String)majorArray.get(i);
System.out.println("专业-" + (i+1) +": "+ m);//专业-1: 后端程序员
//专业-2: 前端程序员
}
JSONArray hobbyArray = jsonObject.getJSONArray("hobby");
System.out.println(hobbyArray);//["篮球","健身","羽毛球"]
for (Object o : hobbyArray) {
System.out.println(o); //篮球
//健身
//羽毛球
}
JSONObject foodsMap = jsonObject.getJSONObject("foodsMap");
System.out.println(foodsMap);//{"food1":"烧烤","food2":"火锅"}
}
}
Case1上述案例结果:
姓名是:pangGe
年龄:22.0岁
有没有女朋友?false
专业-1: 后端程序员
专业-2: 前端程序员
["篮球","健身","羽毛球"]
篮球
健身
羽毛球
{"food1":"烧烤","food2":"火锅"}
Case2----->从文件读取JSON 判断null
package org.example.readjson;
import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
public class ReadJSONFileInfo2 {
public static void main(String[] args) throws IOException, JSONException {
File file = new File(ReadJSONFileInfo2.class.getResource("/pangGeInfo.json").getFile());
String content = FileUtils.readFileToString(file);
JSONObject jsonObject = new JSONObject(content);
if(!jsonObject.isNull("name")) {
System.out.println("姓名是:"+jsonObject.getString("name"));
}
//从文件读取JSON 判断null
if(!jsonObject.isNull("nickname")) { //实质是pangGeInfo.json文件中并没有这个JSON属性
System.out.println("姓名是:"+jsonObject.getString("nickname"));
}
System.out.println("年龄"+jsonObject.getDouble("age"));
System.out.println("有没有女朋友?"+jsonObject.getBoolean("has_girlfriend"));
JSONArray majorArray = jsonObject.getJSONArray("major");
for(int i = 0;i < majorArray.length(); i++) {
String m = (String)majorArray.get(i);
System.out.println("专业-" + (i+1) + m);
}
}
}
Case2上述案例结果:
姓名是:pangGe
年龄22.0
有没有女朋友?false
专业-1后端程序员
专业-2前端程序员