下面是Java读取Json数据并存入数据库的操作代码的攻略,包含以下四个步骤:
- 构建Json数据对象
- 读取Json数据
- 解析Json数据
- 将数据存入数据库
下面进行详细讲解。
步骤一:构建Json数据对象
使用Java构建Json对象可以使用json库的JSONObject类来构建。首先需要导入相应的依赖:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20211205</version>
</dependency>
然后构建Json对象可以这样写:
import org.json.*;
JSONObject jsonObj = new JSONObject();
jsonObj.put("name", "Alice");
jsonObj.put("age", 18);
步骤二:读取Json数据
在读取Json数据之前,需要先将Json数据读入内存。可以从文件或者网络等载体中读入Json数据:
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
// 从文件中读取Json数据
String jsonStr = new String(Files.readAllBytes(Paths.get("data.json")), StandardCharsets.UTF_8);
// 从URL中读取Json数据
URL url = new URL("http://example.com/data.json");
URLConnection conn = url.openConnection();
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String jsonStr = reader.lines().collect(Collectors.joining("\n"));
步骤三:解析Json数据
解析Json数据可以使用json库的JSONObject和JSONArray类来解析。具体方式取决于Json数据的结构。假设Json数据的格式如下:
{
"name": "Alice",
"age": 18,
"address": {
"city": "Shanghai",
"street": "Renmin Rd."
},
"scores": [80, 90, 95]
}
可以这样解析:
JSONObject jsonObj = new JSONObject(jsonStr);
String name = jsonObj.getString("name");
int age = jsonObj.getInt("age");
JSONObject address = jsonObj.getJSONObject("address");
String city = address.getString("city");
String street = address.getString("street");
JSONArray scores = jsonObj.getJSONArray("scores");
List<Integer> scoreList = new ArrayList<>();
for (int i = 0; i < scores.length(); i++) {
scoreList.add(scores.getInt(i));
}
步骤四:将数据存入数据库
将数据存入数据库可以使用JDBC或者ORM框架。这里以JDBC为例。假设要将上面解析出来的数据存入一个名为"person"的表中,表结构如下:
Field | Type | Null | Key | Default | Extra |
---|---|---|---|---|---|
name | varchar(255) | NO | NULL | ||
age | int(11) | NO | NULL | ||
city | varchar(255) | YES | NULL | ||
street | varchar(255) | YES | NULL | ||
score | int(11) | YES | NULL |
可以这样写JDBC代码:
import java.sql.*;
String url = "jdbc:mysql://localhost:3306/test?useSSL=false&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
String username = "root";
String password = "root";
try (Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement stmt = conn.prepareStatement("INSERT INTO person (name, age, city, street, score) VALUES (?, ?, ?, ?, ?)")) {
stmt.setString(1, name);
stmt.setInt(2, age);
stmt.setString(3, city);
stmt.setString(4, street);
for (int score : scoreList) {
stmt.setInt(5, score);
stmt.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
这样就完成了将Json数据存入数据库的操作。下面给出两个示例:
示例一
假设Json数据如下:
{
"name": "Tom",
"age": 23,
"scores": [80, 78, 92]
}
通过上述步骤完成该Json数据的读取、解析并存入数据库的完整代码如下:
import org.json.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.*;
import java.util.*;
import java.util.stream.Collectors;
public class Example1 {
public static void main(String[] args) {
// 从文件中读取Json数据
String jsonStr = "{\"name\": \"Tom\", \"age\": 23, \"scores\": [80, 78, 92]}";
// 构建Json对象
JSONObject jsonObj = new JSONObject(jsonStr);
// 解析Json对象
String name = jsonObj.getString("name");
int age = jsonObj.getInt("age");
JSONArray scores = jsonObj.getJSONArray("scores");
List<Integer> scoreList = new ArrayList<>();
for (int i = 0; i < scores.length(); i++) {
scoreList.add(scores.getInt(i));
}
// 存储数据到数据库
String url = "jdbc:mysql://localhost:3306/test?useSSL=false&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
String username = "root";
String password = "root";
try (Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement stmt = conn.prepareStatement("INSERT INTO person (name, age, score) VALUES (?, ?, ?)")) {
stmt.setString(1, name);
stmt.setInt(2, age);
for (int score : scoreList) {
stmt.setInt(3, score);
stmt.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
执行完该程序后,可以在MySQL数据库中查看如下数据:
name | age | city | street | score |
---|---|---|---|---|
Tom | 23 | NULL | NULL | 80 |
Tom | 23 | NULL | NULL | 78 |
Tom | 23 | NULL | NULL | 92 |
示例二
假设Json数据如下:
{
"name": "Jerry",
"age": 25,
"address": {
"city": "Beijing",
"street": "Haidian"
},
"scores": [85, 92, 88, 90]
}
通过上述步骤完成该Json数据的读取、解析并存入数据库的完整代码如下:
import org.json.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.*;
import java.util.*;
import java.util.stream.Collectors;
public class Example2 {
public static void main(String[] args) {
// 从文件中读取Json数据
String jsonStr = "{\"name\": \"Jerry\", \"age\": 25, \"address\": {\"city\": \"Beijing\", \"street\": \"Haidian\"}, \"scores\": [85, 92, 88, 90]}";
// 构建Json对象
JSONObject jsonObj = new JSONObject(jsonStr);
// 解析Json对象
String name = jsonObj.getString("name");
int age = jsonObj.getInt("age");
JSONObject address = jsonObj.getJSONObject("address");
String city = address.getString("city");
String street = address.getString("street");
JSONArray scores = jsonObj.getJSONArray("scores");
List<Integer> scoreList = new ArrayList<>();
for (int i = 0; i < scores.length(); i++) {
scoreList.add(scores.getInt(i));
}
// 存储数据到数据库
String url = "jdbc:mysql://localhost:3306/test?useSSL=false&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
String username = "root";
String password = "root";
try (Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement stmt = conn.prepareStatement("INSERT INTO person (name, age, city, street, score) VALUES (?, ?, ?, ?, ?)")) {
stmt.setString(1, name);
stmt.setInt(2, age);
stmt.setString(3, city);
stmt.setString(4, street);
for (int score : scoreList) {
stmt.setInt(5, score);
stmt.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
执行完该程序后,可以在MySQL数据库中查看如下数据:
name | age | city | street | score |
---|---|---|---|---|
Jerry | 25 | Beijing | Haidian | 85 |
Jerry | 25 | Beijing | Haidian | 92 |
Jerry | 25 | Beijing | Haidian | 88 |
Jerry | 25 | Beijing | Haidian | 90 |
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java读取json数据并存入数据库的操作代码 - Python技术站