1

所以我迷失了如何做到这一点:目标只是在java中调用openweather api并在控制台上返回结果。我找不到任何关于如何做到这一点的教程,只有关于如何从另一个文件解析 JSON 数据......

嗯,这是朝着正确的方向发展吗?不知道。根据建议修改以尝试使用 Gson

import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonValue;


public class ApiJSONRead {

    URL apiURL = new URL("http://api.openweathermap.org/data/2.5/find?q=London&APPID=(idhere)");

    public static void main(String[] args) throws IOException {



        JsonObject jobj = new Gson().fromJson(apiURL, JsonObject.class);
        var Jsonresponse = jobj.get("weather").getAsString();


        System.out.println(Jsonresponse);

    }

}
4

4 回答 4

1

有点,尽管正如其中一位评论者指出的那样,运行您的代码。它行不通。一旦你得到了流,你所拥有的应该可以工作。但apiURL它不是一个文件,所以FileInputStream不会明白如何阅读它。查看Apache HttpComponents。具体来说,这里有一个示例,展示了如何发出GET请求,这正是您想要做的。

于 2017-02-18T17:28:47.027 回答
1

要解析 JSON 数据,可以使用 google API gson

例如

    JsonObject jobj = new Gson().fromJson(response, JsonObject.class);
    jsonresponse = jobj.get("message").getAsString();
于 2017-02-18T17:37:17.840 回答
1

检查下面的代码并导入必要的罐子

import java.io.IOException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;
import com.google.gson.JsonObject;


public class ApiJSONRead {



    public static void main(String[] args) throws IOException {


        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet("http://ip.jsontest.com/");
        org.apache.http.HttpResponse httpResponse = client.execute(request);
        String response = EntityUtils.toString(httpResponse.getEntity());
        System.out.println(response);
        JsonObject jobj = new Gson().fromJson(response, JsonObject.class);
        String Jsonresponse = jobj.get("ip").getAsString();
        System.out.println(Jsonresponse);
    }

}
于 2017-02-18T18:23:00.180 回答
0

我是 Sprinkler 开源项目的提交者。请参阅http://wiki.bitplan.com/index.php/Sprinkler 作为项目的一部分,我正在实施必要的开放天气 API 调用。你可能想看看

https://github.com/BITPlan/com.bitplan.sprinkler/blob/master/src/test/java/com/bitplan/sprinkler/TestWeatherReport.java

https://github.com/BITPlan/com.bitplan.sprinkler/blob/master/src/main/java/org/openweathermap/weather/WeatherReport.java

还有一个 JsonUtil 帮助类,它隐藏了如何从 url 获取 json 字符串的细节。

于 2018-08-03T09:21:48.710 回答