java json写入本地文件_Json读写本地文件实现代码
时间: 2024-05-03 11:17:44 浏览: 275
下面是Java中使用Gson库实现Json读写本地文件的示例代码:
```java
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.*;
public class JsonFileHandler {
private static final String FILENAME = "data.json"; // 定义文件名
public static void writeToJsonFile(Object object) {
try {
Gson gson = new Gson();
String json = gson.toJson(object);
FileWriter writer = new FileWriter(FILENAME);
writer.write(json);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static <T> T readFromJsonFile(TypeToken<T> typeToken) {
T object = null;
try {
Gson gson = new Gson();
BufferedReader reader = new BufferedReader(new FileReader(FILENAME));
object = gson.fromJson(reader, typeToken.getType());
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return object;
}
}
```
在上述代码中,我们使用了Gson库来实现Json的序列化和反序列化,其中`writeToJsonFile`方法可以将一个Java对象写入到本地的Json文件中,`readFromJsonFile`方法可以从本地的Json文件中读取出一个Java对象。
示例用法:
```java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Person> persons = new ArrayList<>();
persons.add(new Person("Alice", 18));
persons.add(new Person("Bob", 20));
JsonFileHandler.writeToJsonFile(persons); // 将对象写入到本地Json文件中
List<Person> readPersons = JsonFileHandler.readFromJsonFile(new TypeToken<List<Person>>(){}); // 从本地Json文件中读取对象
System.out.println(readPersons);
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
```
运行结果:
```
[Person{name='Alice', age=18}, Person{name='Bob', age=20}]
```
阅读全文