JSON与GSON快速了解

❤️ 随手一写,开始日益积累的行程❤️
❤️目前博主已经转到SOLO如果喜欢大家可以到www.wslhome.top进行查看❤️

JSON与GSON基础(带你快速了解JSON与GSON)

第一部分:JSON基础

一、JSON:json是一种与开发语言无关的轻量级的数据格式

二、类型:

  1. 数据类型:
类型 说明 符号 举例 备注
Object 对象、结构体 { } {“name”:“张三”} key必须为String
Array 数组 [ ] [“test1”,“test2”,“test3”]
  1. 基本类型:
类型 String number true/false null

三、使用:

  1. 依赖可以选择自己使用的方式,这里以maven为例:
pom.xml
<!-- https://mvnrepository.com/artifact/org.json/json -->
  <dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180813</version>
  </dependency> 

  1. json样例:
{
"name":"wangxiaolei",
"age":"21",
"year":"1997-01",
"like":["写代码","陪女友"],
"friends":true,
"has":null
}

PS:JSON中不允许打注视,如果需要注释,可以以key-value的形式存在12、

3.JSON使用
(1)json基本使用

import org.json.JSONObject;

public class main {
    public static void main(String[] args){
        JSONObject jb = new JSONObject();
        jb.put("name","wangxiaolei");
        jb.put("major",new String[]{"java","MySQL"});
        jb.put("has",true);
        System.out.println(jb);
    }
}

(2)Map转化为JSON

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class test {
    public static void main(String[] args){
        Map<String,Object> map= new HashMap<String,Object>();
        map.put("name","wang");
        map.put("test",true);
        map.put("major",new String[]{"JAVA","C++"});
        JSONObject jb = new JSONObject(map);
        System.out.println(jb);
    }
}

(3)类class与JSON的相互转化

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class test {
    public static void main(String[] args){
        Student stu = new Student(1,"wangxiaoer",14,"男");
        JSONObject jb = new JSONObject(stu);
        System.out.println(jb);
    }
}

/*******************************Student.java*******************************/

public class Student {
    private Integer id;
    private String name;
    private Integer age;
    private String sex;

    public Student() {
    }

    public Student(Integer id, String name, Integer age, String sex) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

(3)JSON文件的获取(xxx.json文件读取)

import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
import java.io.*;


public class test {
    public static void main(String[] args) throws IOException {
        File file = new File(ReadJsonSample.class.getResource("Student.json").getFile());
        String content = FileUtils.readFileToString(file);
        JSONObject jb = new JSONObject(content);
        if(jb.isNull("name")){
            System.out.println("name is null");
        }else {
            String name = jb.getString("name");
            System.out.println(name);
        }
    }
}

第二部分:GSON基础

一、GSON:

GSON是Google提供用来转换Java对象和JSON数据的类库,可以将Json字符串转化为Java对象,或者将Java对象转化为JSON字符串

二、配置pom.xml

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>

三、使用

1.GSON与JSON的相互转化


import com.google.gson.Gson;
import org.json.JSONObject;
public class test {
    public static void main(String[] args){
        Gson gson = new Gson();
        /**逻辑省略*/
        JSONObject jb = new JSONObject();
        gson.toJson(jb);
    }
}

2.gson 中key转化(如图,如果没有使用注解SerializedName,则获取的key为name,而使用注解有类似重命名的作用)

@SerializedName("stuName")
    private String name;

3.transient 关键字对gson不可见。当我们在使用transient修饰属性时,属性值对gson不可见

(transient 关键字在使用过程中,不参与成员变量序列化的过程,此处不做介绍)

private transient String name;

4.gson的正向生成反向解析

import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
import java.io.*;


public class test {
    public static void main(String[] args) throws IOException {
        File file = new File(ReadJsonSample.class.getResource("/Student.json").getFile());
        String content = FileUtils.readFileToString(file);
	Gson gson = new Gson();  
	Student objectName =gson.fromJson(content,Student.class);
    }
}

  

5.Gson的时间处理(这是我目前最喜欢的,json不具备时间格式的处理)

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();

6:Gson 自动解析list、set 但是json不会

public class Student{
	private List <String> demoList;

	public List<String> getDemoList() {
		return demoList;
	}
	public void setDemoList(List<String> demoList) {
		this.demoList = demoList;
	}
}

/*******************************************************************/
public class test {
    public static void main(String[] args){
	Student demo = new Gson().fromJson(json,student.class);
	List<String> list = demo.getDemoList();
    }
}

目前博主已经转到SOLO如果喜欢大家可以到www.wslhome.top进行查看

猜你喜欢

转载自blog.csdn.net/qq_40432886/article/details/106321133
今日推荐