likes
comments
collection
share

慕课网_《JSON快速入门(Java版)》学习总结

作者站长头像
站长
· 阅读数 29

时间:2017年05月21日星期日说明:本文部分内容均来自慕课网。@慕课网:http://www.imooc.com教学示例源码:无个人学习源码:https://github.com/zccodere/s...

第一章:课程概述

1-1 JSON课程介绍

课程须知

本课程面向所有使用Java语言进行开发的小伙伴。

JSON是行业内使用最为广泛的数据传输格式课程大纲

JSON基础知识
Java中两种常见的JSON处理方式
综合运用

第二章:基础入门

2-1 什么是JSON

什么是JSON

JSON是一种与开发语言无关的、轻量级的数据格式。全称JavaScript Object Notation。

优点

易于人的阅读和编写
易于程序解析与生成

一个简单的JSON样例

慕课网_《JSON快速入门(Java版)》学习总结

2-2 数据类型表示

数据结构

Object:{}
Array:, []

基本类型

string
number
true
false
null

Object:对象数据结构

使用花括号{}包含的键值对结构,Key必须是string类型,value为任何基本类型或数据结构。

示意图

慕课网_《JSON快速入门(Java版)》学习总结

Array:数组数据格式

使用中括号[]来起始,并用逗号, 来分隔元素。

示意图

慕课网_《JSON快速入门(Java版)》学习总结

2-3 JSON数据演示

代码演示:

{
    "name" : "王小二",
    "age" : 25.2,
    "birthday" : "1990-01-01",
    "school" : "蓝翔",
    "major" : ["理发","挖掘机"],
    "has_girlfriend" : false,
    "car" : null,
    "house" : null,
    "comment" : "这是一个注释"
}

第三章:JSON in Java

3-1 JSON的使用

项目搭建

首先创建一个项目,教学使用maven进行构建,我学习时使用gradle进行构建。因本次课程以学习JSON为主,所以省略项目搭建过程,具体源码可参考我的github地址。

使用JSONObject生成JSON格式数据

代码演示:

/**
 * 通过 JSONObject 生成JSON
 */
private static void createJsonByJsonObject() {
    JSONObject wangxiaoer = new JSONObject();
    // 定义nullObject
    Object nullObject = null;
    wangxiaoer.put("name","王小二");
    wangxiaoer.put("age",25.2);
    wangxiaoer.put("birthday","1990-01-01");
    wangxiaoer.put("school","蓝翔");
    wangxiaoer.put("major",new String[]{"理发","挖掘机"});
    wangxiaoer.put("has_girlfriend",false);
    // 使用nullObject跳过编译器检查
    wangxiaoer.put("car",nullObject);
    wangxiaoer.put("house",nullObject);
    wangxiaoer.put("comment","这是一个注释");

    System.out.println(wangxiaoer.toString());

}

3-2 使用Map构建JSON

代码演示:

/**
 * 通过 HashMap 生成JSON
 */
public static void createJsonByMap(){
    Map<String,Object> wangxiaoer = new HashMap<String,Object>();

    Object nullObject = null;
    wangxiaoer.put("name","王小二");
    wangxiaoer.put("age",25.2);
    wangxiaoer.put("birthday","1990-01-01");
    wangxiaoer.put("school","蓝翔");
    wangxiaoer.put("major",new String[]{"理发","挖掘机"});
    wangxiaoer.put("has_girlfriend",false);
    // 使用nullObject跳过编译器检查
    wangxiaoer.put("car",nullObject);
    wangxiaoer.put("house",nullObject);
    wangxiaoer.put("comment","这是一个注释");
    // 通过 JSONObject 的构造函数接收一个 Map 生成 JSON
    System.out.println(new JSONObject(wangxiaoer).toString());
}

3-3 使用Java Bean构建对象

代码演示:

1.构建JavaBean

package com.myimooc.json.model;

import java.util.Arrays;

/**
 * Created by ChangComputer on 2017/5/21.
 */
public class Diaosi {
    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;
    // 使用 transient 关键字,生成 JSON 时忽略该字段
    private transient String ignore;

    public String getIgnore() {
        return ignore;
    }

    public void setIgnore(String ignore) {
        this.ignore = ignore;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSchool() {
        return school;
    }

    public void setSchool(String school) {
        this.school = school;
    }

    public boolean isHas_girlfriend() {
        return has_girlfriend;
    }

    public void setHas_girlfriend(boolean has_girlfriend) {
        this.has_girlfriend = has_girlfriend;
    }

    public double getAge() {
        return age;
    }

    public void setAge(double age) {
        this.age = age;
    }

    public Object getCar() {
        return car;
    }

    public void setCar(Object car) {
        this.car = car;
    }

    public Object getHouse() {
        return house;
    }

    public void setHouse(Object house) {
        this.house = house;
    }

    public String[] getMajor() {
        return major;
    }

    public void setMajor(String[] major) {
        this.major = major;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "Diaosi{" +
                "name='" + name + '\'' +
                ", school='" + school + '\'' +
                ", has_girlfriend=" + has_girlfriend +
                ", age=" + age +
                ", car=" + car +
                ", house=" + house +
                ", major=" + Arrays.toString(major) +
                ", comment='" + comment + '\'' +
                ", birthday='" + birthday + '\'' +
                ", ignore='" + ignore + '\'' +
                '}';
    }
}

2.编写构建代码

/**
 * 通过 JavaBean 生成JSON【推荐使用】
 */
public static void createJsonByBean(){
    Diaosi wangxiaoer = new Diaosi();

    wangxiaoer.setName("王小二");
    wangxiaoer.setAge(25.2);
    wangxiaoer.setBirthday("1990-01-01");
    wangxiaoer.setSchool("蓝翔");
    wangxiaoer.setMajor(new String[]{"理发","挖掘机"});
    wangxiaoer.setHas_girlfriend(false);
    wangxiaoer.setCar(null);
    wangxiaoer.setHouse(null);
    wangxiaoer.setComment("这是一个注释");

    // 通过 JSONObject 的构造函数接收一个 Bean 生成 JSON
    System.out.println(new JSONObject(wangxiaoer).toString());
}

3-4 从文件读取JSON

代码演示:

1.添加common-io依赖

// https://mvnrepository.com/artifact/commons-io/commons-io
compile group: 'commons-io', name: 'commons-io', version: '2.5'

2.准备JSON数据文件

{
    "name" : "王小二",
    "age" : 25.2,
    "birthday" : "1990-01-01",
    "school" : "蓝翔",
    "major" : ["理发","挖掘机"],
    "has_girlfriend" : false,
    "car" : null,
    "house" : null,
    "comment" : "这是一个注释"
}

3.编写读取代码

package com.myimooc.json.demo;

import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;

/**
 * 读取 JSON 数据演示类
 * Created by ChangComputer on 2017/5/21.
 */
public class ReadJsonSample {

    public static void main(String[] args) throws IOException {
        createJsonByFile();
    }

    /**
     * 读取 JSON 数据
     * */
    public static void createJsonByFile() throws IOException {
        File file = new File(ReadJsonSample.class.getResource("/wangxiaoer.json").getFile());

        String content = FileUtils.readFileToString(file,"UTF-8");

        JSONObject jsonObject = new JSONObject(content);

        System.out.println("姓名:"+jsonObject.getString("name"));
        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++) {
            System.out.println("专业"+(i+1)+":"+majorArray.get(i));
        }

        // 判断属性的值是否为空
        if(!jsonObject.isNull("nickname")){
            System.out.println("昵称:"+jsonObject.getDouble("nickname"));
        }
    }
}

3-5 从文件读取JSON判断null

代码演示:

// 判断属性的值是否为空
if(!jsonObject.isNull("nickname")){
    System.out.println("昵称:"+jsonObject.getDouble("nickname"));
}

3-6 总结

本章总结

讲解了如何生成JSON格式数据
讲解了如何解析JSONObject

第四章:GSON的使用

4-1 GSON介绍

开源地址

https://github.com/google/gson

GSON优点

功能更加强大
性能更加出色
使用方式更加便捷和简单

4-2 GSON生成JSON数据

代码演示:

1.添加依赖

// https://mvnrepository.com/artifact/com.google.code.gson/gson
compile group: 'com.google.code.gson', name: 'gson', version: '2.8.0'

2.编写代码

package com.myimooc.json.gson;

import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.myimooc.json.model.Diaosi;

import java.lang.reflect.Field;

/**
 * 使用 GSON 进行 JSON 相关操作
 * Created by ChangComputer on 2017/5/21.
 */
public class GsonCreateSample {

    public static void main(String[] args) {
        createJsonByGsonBean();
    }

    /**
     *
     * 通过 JavaBean 生成JSON【推荐使用】
     */
    private static void createJsonByGsonBean() {
        Diaosi wangxiaoer = new Diaosi();

        wangxiaoer.setName("王小二");
        wangxiaoer.setAge(25.2);
        wangxiaoer.setBirthday("1990-01-01");
        wangxiaoer.setSchool("蓝翔");
        wangxiaoer.setMajor(new String[]{"理发","挖掘机"});
        wangxiaoer.setHas_girlfriend(false);
        wangxiaoer.setCar(null);
        wangxiaoer.setHouse(null);
        wangxiaoer.setComment("这是一个注释");
        wangxiaoer.setIgnore("不要看见我");

        GsonBuilder gsonBuilder = new GsonBuilder();
        // 设置格式化输出
        gsonBuilder.setPrettyPrinting();
        // 自定义转换策略
        gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy() {
            @Override
            public String translateName(Field f) {
                if(f.getName().equals("name")){
                    return "NAME";
                }
                return f.getName();
            }
        });
        // 生成Gson
        Gson gson = gsonBuilder.create();
        System.out.println(gson.toJson(wangxiaoer));
    }
}

4-3 生成JSON数据

代码演示:

package com.myimooc.json.gson;

import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.myimooc.json.model.Diaosi;

import java.lang.reflect.Field;

/**
 * 使用 GSON 进行 JSON 相关操作
 * Created by ChangComputer on 2017/5/21.
 */
public class GsonCreateSample {

    public static void main(String[] args) {
        createJsonByGsonBean();
    }

    /**
     *
     * 通过 JavaBean 生成JSON【推荐使用】
     */
    private static void createJsonByGsonBean() {
        Diaosi wangxiaoer = new Diaosi();

        wangxiaoer.setName("王小二");
        wangxiaoer.setAge(25.2);
        wangxiaoer.setBirthday("1990-01-01");
        wangxiaoer.setSchool("蓝翔");
        wangxiaoer.setMajor(new String[]{"理发","挖掘机"});
        wangxiaoer.setHas_girlfriend(false);
        wangxiaoer.setCar(null);
        wangxiaoer.setHouse(null);
        wangxiaoer.setComment("这是一个注释");
        wangxiaoer.setIgnore("不要看见我");

        GsonBuilder gsonBuilder = new GsonBuilder();
        // 设置格式化输出
        gsonBuilder.setPrettyPrinting();
        // 自定义转换策略
        gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy() {
            @Override
            public String translateName(Field f) {
                if(f.getName().equals("name")){
                    return "NAME";
                }
                return f.getName();
            }
        });
        // 生成Gson
        Gson gson = gsonBuilder.create();
        System.out.println(gson.toJson(wangxiaoer));
    }
}

4-4 GSON解析

代码演示:

package com.myimooc.json.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.myimooc.json.demo.ReadJsonSample;
import com.myimooc.json.model.Diaosi;
import com.myimooc.json.model.DiaosiWithBirthday;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

/**
 * 使用Gson解析 JSON 文件
 * Created by ChangComputer on 2017/5/21.
 */
public class GsonReadSample {
    public static void main(String[] args) throws IOException {
        createJsonByGsonFile();
    }

    /**
     * 读取 JSON 数据
     * */
    public static void createJsonByGsonFile() throws IOException {
        File file = new File(GsonReadSample.class.getResource("/wangxiaoer.json").getFile());

        String content = FileUtils.readFileToString(file,"UTF-8");

        // 无日期转换
        Gson gson = new Gson();

        Diaosi wangxiaoer = gson.fromJson(content,Diaosi.class);

        System.out.println(wangxiaoer.toString());

        // 带日期转换
        Gson gson2 = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();

        DiaosiWithBirthday wangxiaoer2 = gson2.fromJson(content,DiaosiWithBirthday.class);

        System.out.println(wangxiaoer2.getBirthday().toString());

        // 集合类解析
        System.out.println(wangxiaoer2.getMajor());
        System.out.println(wangxiaoer2.getMajor().getClass());

    }
}

4-5 GSON解析日期转换

代码演示:

// 带日期转换
Gson gson2 = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();

DiaosiWithBirthday wangxiaoer2 = gson2.fromJson(content,DiaosiWithBirthday.class);

System.out.println(wangxiaoer2.getBirthday().toString());

4-6 集合类解析

代码演示:

// 替换为集合类
private List<String> major;

GSON会自动解析集合类字段

 // 集合类解析
System.out.println(wangxiaoer2.getMajor());
System.out.println(wangxiaoer2.getMajor().getClass());

4-7 总结

JSON和GSON

JSON是Android SDK官方的库
GSON适用于服务端开发
GSON比JSON功能更强大

JSON库的特点

功能:映射Java Object与json格式数据
1.通过Annotation注解来声明
2.支持自定义属性名称
3.支持包含或排序属性
4.支持自定义接口自己完成解析或生成过程