要实现Java调用接口获取JSON数据并将其解析后保存到数据库,我们可以按下面的步骤进行操作:
1.发送HTTP请求获取JSON数据
使用Java的HttpUrlConnection或HttpClient等工具发送HTTP请求,获取返回的JSON字符串。
示例代码:
String apiUrl = "https://api.example.com/data.json"; //接口地址
String response = null;
try {
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //打开连接
conn.setRequestMethod("GET"); //设置请求方式
conn.setRequestProperty("Content-Type", "application/json"); //设置请求头
conn.setConnectTimeout(5000); //设置连接超时时间
conn.setReadTimeout(5000); //设置读取超时时间
InputStream inStream = conn.getInputStream(); //获取输入流
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
String inputLine;
StringBuffer responseBuffer = new StringBuffer();
while ((inputLine = reader.readLine()) != null) { //读取返回的字符串,保存到StringBuffer中
responseBuffer.append(inputLine);
}
reader.close();//关闭读取器
response = responseBuffer.toString();//将StringBuffer转化为字符串
conn.disconnect();//断开连接
} catch (Exception e) {
e.printStackTrace();
}
2.解析JSON数据
使用Java的JSON库解析JSON数据。
示例代码:
使用Jackson库解析JSON数据示例:
String json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
ObjectMapper objectMapper = new ObjectMapper();
try {
Map<String, Object> map = objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {});
String name = (String)map.get("name");
int age = (Integer)map.get("age");
String city = (String)map.get("city");
} catch (JsonProcessingException e) {
e.printStackTrace();
}
使用Gson库解析JSON数据示例:
String json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
Gson gson = new Gson();
JsonElement jsonElement = gson.fromJson(json, JsonElement.class);
JsonObject jsonObject = jsonElement.getAsJsonObject();
String name = jsonObject.get("name").getAsString();
int age = jsonObject.get("age").getAsInt();
String city = jsonObject.get("city").getAsString();
3.保存数据到数据库
将解析后的数据保存到数据库中,我们可以使用JDBC或者ORM框架来实现。
示例代码:
使用JDBC插入数据示例:
String name = "John";
int age = 30;
String city = "New York";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
String sql = "INSERT INTO user(name, age, city) VALUES (?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, name);
stmt.setInt(2, age);
stmt.setString(3, city);
stmt.executeUpdate();
stmt.close();
conn.close();
使用Hibernate插入数据示例:
String name = "John";
int age = 30;
String city = "New York";
User user = new User();
user.setName(name);
user.setAge(age);
user.setCity(city);
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.save(user);
transaction.commit();
session.close();
通过以上步骤,我们就可以实现Java调用接口获取JSON数据并将其解析后保存到数据库。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java调用接口如何获取json数据解析后保存到数据库 - Python技术站