简体   繁体   English

Java JSON对象解析

[英]Java JSON object parsing

I am trying to run a Telegram bot that returns current weather (with help of user's detected ip from another function), but the JSON parsing does not work properly. 我正在尝试运行一个返回当前天气的Telegram机器人(借助于用户从另一个函数中检测到的ip),但是JSON解析无法正常工作。 I get "Exception in thread "null Telegram Executor" java.lang.StackOverflowError" from last row before return. 返回前,我从最后一行得到“线程“空电报执行程序” java.lang.StackOverflowError中的异常”。 Another approach to this yielded "null pointer exception", where i followed a example from here. 对此的另一种方法产生了“空指针异常”,在这里我遵循一个示例。

Any way to parse a JSON with java and GSON? 用Java和GSON解析JSON的任何方法吗?

public String palautaSaatila() throws MalformedURLException, IOException {

    String sURL = "http://api.wunderground.com/api/" + wundergroundApikey + "/conditions/q/" + valtio + "/" + kaupunki + ".json";
    System.out.println(sURL);
    // Connect to the URL using java's native library
    URL url = new URL(sURL);
    HttpURLConnection request = (HttpURLConnection) url.openConnection();
    request.connect();
    System.out.println("Connect ok");

    // Convert to a JSON object to print data
    JsonParser jp = new JsonParser(); //from gson
    JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
    JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object. 
    String tempSaatila = new JSONObject(rootobj).toString(2);

    return tempSaatila;
}

The JSON response looks like this, i only need the "weather" key: JSON响应如下所示,我只需要“天气”键即可:

{
  "response": {
    "version":"0.1",
  "termsofService":"http://www.wunderground.com/weather/api/d/terms.html",
    "features": {
        "conditions": 1
    }
  },
  "current_observation": {
    "image": {
      "url":"http://icons.wxug.com/graphics/wu2/logo_130x80.png",
      "title":"Weather Underground",
      "link":"http://www.wunderground.com"
    },
    "display_location": {
      "full":"Oulu, Finland",
      "city":"Oulu",
      "state":"",
      "state_name":"Finland",
      "country":"FI",
      "country_iso3166":"FI",
      "zip":"00000",
      "magic":"138",
      "wmo":"02876",
      "latitude":"65.01999664",
      "longitude":"25.46999931",
      "elevation":"14.9"
    },
    "observation_location": {
      "full":"Oulu, Oulu, ",
      "city":"Oulu, Oulu",
      "state":"",
      "country":"FI",
      "country_iso3166":"FI",
      "latitude":"64.984344",
      "longitude":"25.499750",
      "elevation":"30 ft"
    },
    "estimated": {
    },
    "station_id":"IOULU38",
    "observation_time":"Last Updated on October 19, 9:17 PM EEST",
    "observation_time_rfc822":"Thu, 19 Oct 2017 21:17:35 +0300",
    "observation_epoch":"1508437055",
    "local_time_rfc822":"Thu, 19 Oct 2017 21:18:13 +0300",
    "local_epoch":"1508437093",
    "local_tz_short":"EEST",
    "local_tz_long":"Europe/Helsinki",
    "local_tz_offset":"+0300",
    "weather":"Mostly Cloudy",
    "temperature_string":"34.2 F (1.2 C)",
    "temp_f":34.2,
    "temp_c":1.2,
    "relative_humidity":"99%",
    "wind_string":"Calm",
    "wind_dir":"SW",
    "wind_degrees":233,
    "wind_mph":0.0,
    "wind_gust_mph":0,
    "wind_kph":0,
    "wind_gust_kph":0,
    "pressure_mb":"1018",
    "pressure_in":"30.06",
    "pressure_trend":"0",
    "dewpoint_string":"34 F (1 C)",
    "dewpoint_f":34,
    "dewpoint_c":1,
    "heat_index_string":"NA",
    "heat_index_f":"NA",
    "heat_index_c":"NA",
    "windchill_string":"34 F (1 C)",
    "windchill_f":"34",
    "windchill_c":"1",
    "feelslike_string":"34 F (1 C)",
    "feelslike_f":"34",
    "feelslike_c":"1",
    "visibility_mi":"6.2",
    "visibility_km":"10.0",
    "solarradiation":"0",
    "UV":"0.0","precip_1hr_string":"0.00 in ( 0 mm)",
    "precip_1hr_in":"0.00",
    "precip_1hr_metric":" 0",
    "precip_today_string":"0.00 in (0 mm)",
    "precip_today_in":"0.00",
    "precip_today_metric":"0",
    "icon":"mostlycloudy",
    "icon_url":"http://icons.wxug.com/i/c/k/nt_mostlycloudy.gif",
    "forecast_url":"http://www.wunderground.com/global/stations/02876.html",
    "history_url":"http://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID=IOULU38",
    "ob_url":"http://www.wunderground.com/cgi-bin/findweather/getForecast?query=64.984344,25.499750",
    "nowcast":""
  }
}

Your StackOverflowError is a result of trying to serialise the root gson JsonObject as json with a second library (the org.json.JSONObject wrapper): 您的StackOverflowError是尝试使用第二个库( org.json.JSONObject包装器)将根gson JsonObject序列化为json的org.json.JSONObject

String tempSaatila = new JSONObject(rootobj).toString(2);

You've already parsed the file with gson and can use its API to find the node you want: 您已经使用gson解析了文件,可以使用其API查找所需的节点:

return rootobj
    .getAsJsonObject("current_observation")
    .get("weather")
    .getAsString();

If you want to pretty-print a node with gson you can do it like this: 如果要用gson漂亮地打印一个节点,可以这样:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(rootobj);
System.out.println(json); 

You can parse the JSON string using GSON example below 您可以使用下面的GSON示例解析JSON字符串

    Gson gson = new Gson();
    JsonObject jsonObject = gson.fromJson(json, JsonObject.class);
    JsonObject currentObservation = jsonObject.get("current_observation").getAsJsonObject();

    String weather = currentObservation.get("weather").getAsString();
    System.out.println("weather = " + weather);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM