四、Java核心技术(进阶)-JSON

一、概念

JSON (JavaScript Object Notation),JS对象表示法。独立编程语言,是一种轻量级的数据交换格式,与XML类似,更小、更快、更易解析。

二、语法

JSON对象:名称/键值对,

  • 如{“name:”jo",“email”:"asd@sd.com"}
  • 数据在键值对中,数据由逗号分隔, 花括号保存对象

JSON数组:方括号保存数组,

  • 如[{“name:”jo",“email”:"asd@sd.com"},{“name:”jo1",“email”:"asd1@sd.com"}]

三、实践

org.jason:JSON官方推荐解析类

  • 简单易用,通用性强
  • 复杂功能欠缺

GSON:Google出品

  • 基于反射,可以实现JSON对象、JSON字符串和Java对象互转

Jackson:号称最快的JSON处理器

  • 简单易用,社区更新和发布速度比较快

JASON与XML比较

  • 共同点:都是数据交换格式,可读性强,可扩展性高
  • 优势:大部分情况,JSON更方便转换,效率更高;XML更加注重标签和顺序
  • 缺点:XML转JSON时,JSON会丢失信息(XML注重顺序,JSON不然)

实践内容:

  1. Object --> JSON
  2. JSON --> Object
  3. JSON File --> Object

maven依赖(pom.xml):

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20230227</version>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.1</version>
        </dependency>

类:Book.java

public class Book {
    private String category;
    private String title;
    private String author;
    private String year;
    private int price;
}

类:Books.java

public class Books {
    private List<Book> books;
}

JSON文件:books.json

{
  "books":
  [
    {"year":"2020","author":"sam","price":19,"category":"WEB","title":"python"},
    {"year":"2021","author":"sam","price":15,"category":"Photo","title":"Tree"}
  ]
}

代码:JsonReader.java

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: Shism
 * @Date: Created in 9:06 2023/3/29
 * @Description:
 **/
public class JsonReader {
    public static final String filePath = ".//src//main//resources//books.json";
    public static void main(String[] args) throws IOException {
        JsonReader.proficialJson();
        JsonReader.gsonTest();
        JsonReader.jackSon();
    }

    public static void proficialJson() {
        System.out.println("================proficialJson using==================");
        //生成类
        Book  book = new Book("WEB","python","sam","2020",19);

        //生成Json对象
        JSONObject obj = new JSONObject();
        obj.put("category",book.getCategory());
        obj.put("title",book.getTitle());
        obj.put("author",book.getAuthor());
        obj.put("year",book.getYear());
        obj.put("price",book.getPrice());

        System.out.println(obj);

        //读取json文件
        System.out.println("proficialJson read from file");
        File file = new File(filePath);
        try {
            FileReader reader = new FileReader(file);
            char [] chars = new char[(int)file.length()];
            //读取文件到buffer
            reader.read(chars);
            JSONObject object = new JSONObject(String.valueOf(chars));

            //解析JSON数据,json数组key值
            JSONArray books = object.getJSONArray("books");
            List<Book> bookList = new ArrayList<>();
            //读取json
            for (Object b:books){
                JSONObject js = (JSONObject) b;
                Book getBook = new Book();
                getBook.setTitle(js.getString("title"));
                getBook.setAuthor(js.getString("author"));
                getBook.setCategory(js.getString("category"));
                getBook.setYear(js.getString("year"));
                getBook.setPrice(js.getInt("price"));
                bookList.add(getBook);
            }
            System.out.println(bookList);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void gsonTest() throws IOException {
        System.out.println("===================googelGson using====================");
        //生成类
        Book  book = new Book("WEB","python","sam","2020",19);
        //类->json
        String jsonStr = new Gson().toJson(book);
        System.out.println("class to Json:"+jsonStr);
        //json->类
        Book b = new Gson().fromJson(jsonStr, Book.class);
        System.out.println("json to class:"+b);

        //File read 读取
        Gson gson = new Gson();
        File file = new File(filePath);

        try (FileReader reader = new FileReader(file)) {
            System.out.println("GSON:get json from filepath");
            Books Books = gson.fromJson(reader, new TypeToken<Books>(){}.getType());
            for (Book cell : Books.getBooks()){
                System.out.println(cell);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {

        }

    }


    public static void jackSon() throws IOException {
        System.out.println("================jackSon using==================");
        ObjectMapper om = new ObjectMapper();
        Book book = new Book("web", "earthQuake", "sam", "2020", 25);
        //解析为json字符串
        String bookJson = om.writeValueAsString(book);
        System.out.println("class to json :"+ bookJson);
        //json字符串解析为对象
        Book book1 = om.readValue(bookJson, Book.class);
        System.out.println("json to class :" + book1);

        //从文件中读取转为对象
        File file = new File(filePath);
        System.out.println("Jackson : get json from filepath");
        Books books = om.readValue(file, Books.class);
        for (Book cell : books.getBooks()){
            System.out.println(cell);
        }

    }

}

输出:

================proficialJson using==================
{"year":"2020","author":"sam","price":19,"category":"WEB","title":"python"}
proficialJson read from file
[Book{category='WEB', title='python', author='sam', year='2020', price=19}, Book{category='Photo', title='Tree', author='sam', year='2021', price=15}]
===================googelGson using====================
class to Json:{"category":"WEB","title":"python","author":"sam","year":"2020","price":19}
json to class:Book{category='WEB', title='python', author='sam', year='2020', price=19}
GSON:get json from filepath
Book{category='WEB', title='python', author='sam', year='2020', price=19}
Book{category='Photo', title='Tree', author='sam', year='2021', price=15}
================jackSon using==================
class to json :{"category":"web","title":"earthQuake","author":"sam","year":"2020","price":25}
json to class 锛�Book{category='web', title='earthQuake', author='sam', year='2020', price=25}
Jackson : get json from filepath
Book{category='WEB', title='python', author='sam', year='2020', price=19}
Book{category='Photo', title='Tree', author='sam', year='2021', price=15}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值