从 Java 中的 JSON 文件中检索特定字段

Retrieving specific fields from JSON file in Java

我正在尝试从 Wunderground.com 中检索的 JSON file 中检索特定字段。

我试图post这里面的相关信息,但是无法正确格式化。我正在尝试检索 "current_observation" 部分下的经度和纬度。我正在使用 Gson 2.2.4。这是我目前拥有的代码:

    String key = "aaaaaaaaaaaaaaaa";
    String sURL = "http://api.wunderground.com/api/" + key + "/conditions/forecast/q/19104.json";

    URL url = new URL(sURL);
    URLConnection request = (URLConnection) url.openConnection();
    request.connect();

    JsonParser jp = new JsonParser(); //from gson
    JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
    JsonObject rootobj = root.getAsJsonObject(); 
    JsonElement latitude = rootobj.get("current_observation");

    System.out.println(latitude);

当前获取 "current_observation" 标签下的所有内容,并将其打印到屏幕上。我不知道如何访问那之下的任何东西。我在这里看到了几个关于使用 JsonArray 的 post,但是无论我尝试了什么,我都无法让它正常工作。那么如何从 JSON 文件中检索特定字段?感谢您给我的任何指导,如果我需要提供任何其他信息,请告诉我。

A JsonElement 是一个通用接口,它由两个重要的其他 类 子类化,它们是 JsonArrayJsonObject

由于您没有为 Gson 提供一种类型来反映来自(并填充相应对象)的信息,因此您必须手动进行。由于 "current_observation" 是字典类型,因此它是 JsonObject 并且您可以这样做:

 JsonObject observation = root.getAsJsonObject().get("current_observation").getAsJsonObject();

此时您可以像以前一样检索特定字段:

float longitude = observation.get("longitude").getAsFloat();

等等。

对于特定字段,您可能需要提供自定义解串器或序列化器。实际上最好的解决方案是将您的镜像结构放在代码库中,例如:

class Observation
{
  float latitude;
  float longitude;
  // other fields you are interested in
}

以便您可以提供自己的 deserializer 并执行:

Observation observation = gson.fromJson(root.getAsJsonObject().get("current_observation"), Observation.class)

然后让 Gson 来做脏活累活。

现在您的 current_observation JSON 本身包含一些 JSON 以及 String 文件。我会告诉你 1 个字符串字段 station_id 和其他 JSON 字段 image。你可以这样使用 :-

            JsonParser jp = new JsonParser(); //from gson
            JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
            JsonObject rootobj = root.getAsJsonObject(); 
            JSONObject curObs = (JSONObject)rootobj.get("current_observation");
            JSONObject image = (JSONObject)curObs.get("image"); // image is a JSON
            String imageUrl= (String)image.get("url"); // get image url
            String stationId = (String)curObs.get("station_id"); // get StationId

同样,您也可以对 JSON 的其他属性执行此操作。希望这对您有所帮助。