Java调接口返回的复杂JSON数据存储方案

在现代应用中,很多系统需要通过API接口获取复杂的JSON数据。当我们获取到这些数据后,如何将它们存储到数据库中就成为一个重要的课题。本文将以Java为例,展示如何解析复杂的JSON数据并将其存储到数据库中。

需求分析

假设我们从一个天气API接口获取到以下复杂的JSON数据:

{
  "location": {
    "city": "Shanghai",
    "country": "China"
  },
  "current": {
    "temperature": 28,
    "humidity": 70,
    "weather": "Sunny"
  },
  "forecast": [
    {
      "date": "2023-10-01",
      "high": 30,
      "low": 22,
      "condition": "Sunny"
    },
    {
      "date": "2023-10-02",
      "high": 29,
      "low": 21,
      "condition": "Cloudy"
    }
  ]
}

我们的目标是将这个数据存储到关系型数据库(如MySQL)中。

解决方案

我们将通过以下几个步骤来完成这个问题的解决方案:

  1. 获取JSON数据
  2. 解析JSON
  3. 存储数据到数据库
  4. 验证数据存储

步骤详解

1. 获取JSON数据

通过Java的HTTP客户端,我们可以获取到JSON数据:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class ApiClient {
    public String getWeatherData() throws Exception {
        URL url = new URL("
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder content = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null) {
            content.append(line);
        }
        in.close();
        return content.toString();
    }
}
2. 解析JSON数据

我们可以使用Jackson库来解析复杂的JSON。首先,定义对应的Java类:

import com.fasterxml.jackson.databind.ObjectMapper;

public class WeatherData {
    public Location location;
    public Current current;
    public List<Forecast> forecast;

    public static class Location {
        public String city;
        public String country;
    }

    public static class Current {
        public int temperature;
        public int humidity;
        public String weather;
    }

    public static class Forecast {
        public String date;
        public int high;
        public int low;
        public String condition;
    }
}

// 解析JSON
ObjectMapper objectMapper = new ObjectMapper();
WeatherData weatherData = objectMapper.readValue(jsonResponse, WeatherData.class);
3. 存储数据到数据库

使用JDBC将数据存储到MySQL中:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class DatabaseHandler {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/weather_db";
    private static final String USER = "root";
    private static final String PASS = "password";

    public void insertWeatherData(WeatherData weatherData) throws Exception {
        Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
        String sql = "INSERT INTO weather(location_city, location_country, current_temperature, current_humidity, forecast_date, forecast_high, forecast_low, forecast_condition) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        PreparedStatement pstmt = conn.prepareStatement(sql);

        // 插入当前天气
        pstmt.setString(1, weatherData.location.city);
        pstmt.setString(2, weatherData.location.country);
        pstmt.setInt(3, weatherData.current.temperature);
        pstmt.setInt(4, weatherData.current.humidity);

        // 插入预报数据
        for (Forecast f : weatherData.forecast) {
            pstmt.setString(5, f.date);
            pstmt.setInt(6, f.high);
            pstmt.setInt(7, f.low);
            pstmt.setString(8, f.condition);
            pstmt.executeUpdate();
        }

        pstmt.close();
        conn.close();
    }
}
4. 验证数据存储

通过简单的查询语句验证数据是否存储成功。

流程图

flowchart TD
    A[获取JSON数据] --> B[解析JSON]
    B --> C[存储数据到数据库]
    C --> D[验证数据存储]

数据存储概况

为了概览存储的数据,我们也可以使用饼状图来展示不同天气条件的分布。

pie
    title 天气条件分布
    "Sunny": 60
    "Cloudy": 30
    "Rainy": 10

结论

通过上述步骤,我们成功地将一个复杂的JSON数据存储到了数据库中。使用Java的HTTP客户端获取数据,通过Jackson解析JSON,然后使用JDBC将数据写入MySQL数据库。这样的流程不仅高效而且容易扩展,使得在面对其他类似问题时,能够快速应用和调整。希望这个方案对你有所帮助!