【问题标题】:How to store online JSON API in SQLite如何在 SQLite 中存储在线 JSON API
【发布时间】:2022-01-24 15:26:39
【问题描述】:

所以我正在尝试开发这个应用程序,它使用 Android Studio 将天气详细信息存储到 sqlite 数据库中。我目前正在观看有关如何将 json 数据存储到 SQLite 数据库的教程,但这是从 JSON 文件中读取的。

private String readJsonDataFromFile() throws IOException {

    InputStream inputStream = null;
    StringBuilder builder = new StringBuilder();

    try {
        String jsonDataString = null;
        inputStream = mResources.openRawResource(R.raw.menu_item);
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(inputStream, "UTF-8"));
        while ((jsonDataString = bufferedReader.readLine()) != null) {
            builder.append(jsonDataString);
        }
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }

    return new String(builder);
}
}

例如,他正在读取一个名为 menu_item 的 JSON 文件。如果我想用它来存储来自 MetaWeather api 的数据,我将如何实现上面的代码来工作,例如:https://www.metaweather.com/api/location/search/?query=paris

【问题讨论】:

    标签: java android database api sqlite


    【解决方案1】:

    您可以使用 http 库从我推荐的 api 调用中检索响应 OkHttphttps://square.github.io/okhttp/

    您将收到来自 API 调用的响应正文作为字符串,并且在您获得字符串后,其他所有内容都应与您发布的代码相同。

    OkHttpClient client = new OkHttpClient();
    
    String run(String url) throws IOException {
      Request request = new Request.Builder()
          .url(url)
          .build();
    
      try (Response response = client.newCall(request).execute()) {
        return response.body().string();
      }
    }
    //HERE
    run("https://www.metaweather.com/api/location/search/?query=paris")
    

    【讨论】:

      猜你喜欢
      • 2012-01-12
      • 1970-01-01
      • 2013-04-22
      • 2019-07-18
      • 2013-05-12
      • 2011-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多