Java document operation - json parsing

Author: San Nian

Java document operation - json parsing


1. A brief explanation of the concept:

1. [json jar package] A lightweight data storage and exchange format
Download : www.json.org

2. [Basic structure of json]

  • Use : to save key-value pairs, use, to separate different key-value pairs
  • Use { } to save an object
  • Use [ ] to store an array
    Example :
 [{"id":1,"name":"苹果","price":3.0, "count":51},
 {"id":2,"name":"香蕉","price":3.5, "count":17}]

Second, code analysis:

1. First there is a Person class

import java.io.Serializable;

public class Person implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private String name;
    private int age;
    private String job;

    public Person() {
        super();
    }

    public Person(String name, int age, String job) {
        super();
        this.name = name;
        this.age = age;
        this.job = job;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + ", job=" + job + "]";
    }

}

2. SN_9IO_JSON test class


import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;


public class SN_9IO_JSON {
    public static void main(String[] args) {
        //创建对象
        ArrayList<Person> personList = new ArrayList<>();
        personList.add(new Person("小一", 1, "工作1"));
        personList.add(new Person("小二", 2, "工作2"));
        personList.add(new Person("小三", 3, "工作3"));
        personList.add(new Person("小四", 4, "工作4"));
        personList.add(new Person("小五", 5, "工作5"));
        //保存对象
        save(personList);
        //读取解析对象
        List<Person> load = load();
        for (Person person : load) {
            System.out.println(person);
        }
    }
    /**
     * 用json方式保存到文件
     */
    public static void save(ArrayList<Person> personList) {
        Gson gson = new Gson();
        String json = gson.toJson(personList);
        saveToFile(json);
    }
    /**
     * 写入文件
     * @param con
     */
    public static void saveToFile(String con) {
        FileWriter fw = null;
        try {
            fw = new FileWriter("JSON.json");
            fw.write(con);
            System.out.println("写入成功");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * json解析
     * @return
     */
    public static List<Person> load(){
        ArrayList<Person> arrayList = new ArrayList<>();
        JsonParser jsonParser = new JsonParser();
        try {
            FileReader fr = new FileReader("JSON.json");
            //解析
            JsonArray array = (JsonArray)jsonParser.parse(fr);

            for (int i = 0; i < array.size(); i++) {
                //获取对象属性值
                JsonObject obj = (JsonObject)array.get(i);
                String name = obj.get("name").getAsString();
                int age = obj.get("age").getAsInt();
                String job = obj.get("job").getAsString();
                //添加到列表
                arrayList.add(new Person(name, age, job));
            }
        } catch (JsonIOException | JsonSyntaxException | FileNotFoundException e) {
            e.printStackTrace();
        }

        return arrayList;
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326699589&siteId=291194637