Java parses json data and modifies data in local json files

1. Why do we need to operate json data

In our usual practice, when the database cannot be used, we usually store the simulation data in the local json file, but it is very difficult for us to modify and add it, which includes the analysis data, Modify the data before writing the data. However, under the pressure of the teacher, I had to use this plan. If I talk too much, I will be in tears...

2. Get to the point

(1) The first step is to parse the data

Regarding how to parse json data, my last blog explained the operation process in detail, you can go there and have a look

The address is posted here: Java GUI implements login and registration services, and stores user information in local JSON files (nanny-level tutorial, from new project to running project)_jack doesn't want to be bald blog-CSDN Blog

(2) Since we want to modify the data, we definitely need some original data. At this time, we can simulate some basic user data, create a new data.json file locally, and write some data by hand

[
  {
    "id": 1,
    "name": "John",
    "age": 25
  },
  {
    "id": 2,
    "name": "Lucy",
    "age": 35
  },
  {
    "id": 3,
    "name": "Bob",
    "age": 35
  }
]

(3) To have data, you must create a new Javabean about the data. About how to create Java, it was also mentioned in the previous blog. If you don’t know it, you can go there to see it.


class Data {
    private int id;
    private String name;
    private int age;

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

    public Data() {
    }

    public Data(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

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

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

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

(4) The last step is to modify the data, and then write the new data into the original json file

Core code:

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.*;
import java.util.ArrayList;

public class update {
    public static void main(String[] args) {
        //读取用户数据存放到ArrayList集合当中
        try (BufferedReader br = new BufferedReader(new FileReader("data.json文件地址"))) {
            String json = "";
            String line;
            while ((line = br.readLine()) != null) {
                json += line + "\n";
            }
            Gson gson = new Gson();
            ArrayList<Data> dataList = gson.fromJson(json, new TypeToken<ArrayList<Data>>() {
            }.getType());
            //修改用户数据
            int index = 0;//用户的下标
            dataList.get(index).setName("zs");//设置用户的新信息
            dataList.get(index).setAge(18);
            String jsonString = gson.toJson(dataList); // 将List<User>对象转换为JSON字符串
            //将新数据写入data.json文件中(此时修改原有的数据,但其他数据不会改变)
            File file = new File("data.json文件地址");
            BufferedWriter writer = null; // 创建BufferedWriter对象
            try {
                writer = new BufferedWriter(new FileWriter(file));
                writer.write(jsonString); // 将JSON字符串写入文件
                writer.close(); // 关闭BufferedWriter对象
                System.out.println("数据修改成功");
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The most important part here is to convert the original ArrayList collection into a json string through gson's toJson method, where idnex is the user's subscript, which can be flexibly controlled, and file writing is also the most basic File cooperation BufferedWriter, after running the code, you can see that the json file has changed. It turns out that "John" has been overwritten by "zs".

 So far, modifying the local json file data is over.

Guess you like

Origin blog.csdn.net/m0_64642443/article/details/131067170