Java操作本地JSON文件:从读取到解析的完整指南
在Java开发中,处理JSON(JavaScript Object Notation)数据是一项常见任务,尤其是在配置文件、数据交换和API交互等场景,本文将详细介绍如何使用Java操作本地JSON文件,包括读取、解析、修改和写入JSON数据的完整流程。
准备工作:选择合适的JSON库
Java标准库中没有内置的JSON处理类,因此我们需要借助第三方库,目前最流行的JSON处理库有:
- Gson:Google开发的JSON库,简单易用
- Jackson:功能强大,性能优秀,Spring框架默认使用
- org.json:轻量级库,API简洁
本文将以Gson和Jackson为例进行讲解,因为它们使用广泛且文档完善。
添加依赖
Maven依赖(Gson):
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
Maven依赖(Jackson):
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
读取本地JSON文件
使用Gson读取JSON文件
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.io.FileReader;
import java.io.IOException;
public class GsonJsonReader {
public static void main(String[] args) {
Gson gson = new Gson();
try (FileReader reader = new FileReader("data.json")) {
// 读取JSON文件为JsonObject
JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
System.out.println("JSON内容: " + jsonObject);
// 获取特定字段值
String name = jsonObject.get("name").getAsString();
int age = jsonObject.get("age").getAsInt();
System.out.println("姓名: " + name + ", 年龄: " + age);
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用Jackson读取JSON文件
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import java.io.File;
import java.io.IOException;
public class JacksonJsonReader {
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
try {
// 读取JSON文件为JsonNode
JsonNode rootNode = objectMapper.readTree(new File("data.json"));
System.out.println("JSON内容: " + rootNode);
// 获取特定字段值
String name = rootNode.get("name").asText();
int age = rootNode.get("age").asInt();
System.out.println("姓名: " + name + ", 年龄: " + age);
} catch (IOException e) {
e.printStackTrace();
}
}
}
解析JSON数据为Java对象
定义Java类
首先定义与JSON结构对应的Java类:
public class Person {
private String name;
private int age;
private String[] hobbies;
// 必须有无参构造函数
public Person() {}
// Getter和Setter方法
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[] getHobbies() { return hobbies; }
public void setHobbies(String[] hobbies) { this.hobbies = hobbies; }
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age +
", hobbies=" + Arrays.toString(hobbies) + "}";
}
}
使用Gson解析为Java对象
import com.google.gson.Gson;
import java.io.FileReader;
import java.io.IOException;
public class GsonJsonToObject {
public static void main(String[] args) {
Gson gson = new Gson();
try (FileReader reader = new FileReader("person.json")) {
// 将JSON解析为Person对象
Person person = gson.fromJson(reader, Person.class);
System.out.println("解析后的对象: " + person);
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用Jackson解析为Java对象
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
public class JacksonJsonToObject {
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
try {
// 将JSON解析为Person对象
Person person = objectMapper.readValue(new File("person.json"), Person.class);
System.out.println("解析后的对象: " + person);
} catch (IOException e) {
e.printStackTrace();
}
}
}
修改JSON数据
使用Gson修改JSON
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class GsonJsonModifier {
public static void main(String[] args) {
Gson gson = new Gson();
try (FileReader reader = new FileReader("data.json");
FileWriter writer = new FileWriter("data_modified.json")) {
// 读取JSON
JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
// 修改数据
jsonObject.addProperty("age", 30);
jsonObject.add("newField", gson.toJsonTree("newValue"));
// 写回文件
gson.toJson(jsonObject, writer);
System.out.println("JSON修改完成并已保存");
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用Jackson修改JSON
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.File;
import java.io.IOException;
public class JacksonJsonModifier {
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
try {
// 读取JSON
JsonNode rootNode = objectMapper.readTree(new File("data.json"));
// 修改数据
((ObjectNode) rootNode).put("age", 30);
((ObjectNode) rootNode).put("newField", "newValue");
// 写回文件
objectMapper.writeValue(new File("data_modified.json"), rootNode);
System.out.println("JSON修改完成并已保存");
} catch (IOException e) {
e.printStackTrace();
}
}
}
将Java对象写入JSON文件
使用Gson写入JSON
import com.google.gson.Gson;
import java.io.FileWriter;
import java.io.IOException;
public class GsonJsonWriter {
public static void main(String[] args) {
Gson gson = new Gson();
try (FileWriter writer = new FileWriter("person_output.json")) {
// 创建Java对象
Person person = new Person();
person.setName("张三");
person.setAge(25);
person.setHobbies(new String[]{"阅读", "旅行", "编程"});
// 将对象转换为JSON并写入文件
gson.toJson(person, writer);
System.out.println("Java对象已写入JSON文件");
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用Jackson写入JSON
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
public class JacksonJsonWriter {
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
try {
// 创建Java对象
Person person = new Person();
person.setName("李四");
person.setAge(28);
person.setHobbies(new String[]{"音乐", "运动", "电影"});
// 将对象转换为JSON并写入文件
objectMapper.writeValue(new File("person_output.json"), person);
System.out.println("Java对象已写入JSON文件");
} catch (IOException e) {
e.printStackTrace();
}
}
}
处理复杂JSON结构
对于复杂的JSON结构(如嵌套对象、数组等),可以通过以下方式处理:
嵌套对象示例
{
"name": "王五",
"address": {
"street": "科技路",
"city": "北京",
"zipCode": "100000"
},
"phones": ["13800138000", "13900139000"]
}
对应的Java类:
public class PersonWithAddress {
private String name;
private Address address;
private List<String> phones;
// Getter和Setter方法
// Address类需要单独定义
}
public class Address {
private String street;
private String city;
private String zipCode;
// Getter和Setter方法
}
使用Gson处理复杂结构
Gson gson = new Gson(); PersonWithAddress person = gson.fromJson(jsonString, PersonWithAddress.class);
使用Jackson处理复杂结构
ObjectMapper mapper = new ObjectMapper(); Person



还没有评论,来说两句吧...