使用 Java 从 google Weather API 中提取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10487508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:16:18  来源:igfitidea点击:

Using Java to extract data from google Weather API

javaapiweather

提问by A_Elric

Edit: 2020 update -- Please disregard the question below as Google's weather API is no longer able to be used. If you are interested in using a weather API, Darksky is the defacto that most people use: https://darksky.net/dev

编辑:2020 年更新——请忽略以下问题,因为 Google 的天气 API 不再能够使用。如果您对使用天气 API 感兴趣,Darksky 是大多数人使用的事实:https://darksky.net/dev

If you use Java, the normal way to parse the JSON is using org.json: https://devqa.io/java/how-to-parse-json-in-java

如果您使用 Java,解析 JSON 的正常方法是使用 org.json:https://devqa.io/java/how-to-parse-json-in-java

--

——

Original question below.

下面的原始问题。



I've been playing around with xml documents and java a bit recently, but I've had absolutely no luck using the google weather API.

我最近一直在玩 xml 文档和 java,但我绝对没有使用谷歌天气 API 的运气。

Let's assume that I'm trying to do a simple object to store current temp, and forecast temp for just tomorrow, how would I do this?

让我们假设我正在尝试做一个简单的对象来存储当前温度,并预测明天的温度,我该怎么做?

http://www.google.com/ig/api?weather=02110Is the working example for my home city.

http://www.google.com/ig/api?weather=02110是我家乡城市的工作示例。

Thanks

谢谢

Using this code:

使用此代码:

public static final String[] xmlLoader(){
    String xmlData[] = new String[2];
    try {
        URL googleWeatherXml = new URL("http://www.google.com/ig/api?weather=02110");
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();    
        Document doc = db.parse(googleWeatherXml.openStream());

         // normalize text representation
        doc.getDocumentElement ().normalize ();
        NodeList listOfWeek = doc.getElementsByTagName("");

            Node firstWeekNode = listOfWeek.item(dateCounter-1);
            int totalWeeks = listOfWeek.getLength();


            //Break xml file into parts, then break those parts down int an array by passing individual elements to srtings
            if(firstWeekNode.getNodeType() == Node.ELEMENT_NODE){
                Element firstWeekElement = (Element)firstWeekNode;
                //-------
                NodeList dateList = firstWeekElement.getElementsByTagName("date");
                Element dateElement = (Element)dateList.item(0);

                NodeList textDateList = dateElement.getChildNodes();
                xmlData[0]= (((Node)textDateList.item(0)).getNodeValue().trim()).toString();

                //-------
                NodeList riddleList = firstWeekElement.getElementsByTagName("riddle");
                Element riddleElement = (Element)riddleList.item(0);

                NodeList textRiddleList = riddleElement.getChildNodes();
                xmlData[1]= (((Node)textRiddleList.item(0)).getNodeValue().trim()).toString();

                //----
                NodeList lWSList = firstWeekElement.getElementsByTagName("lastWeekSolution");
                Element ageElement = (Element)lWSList.item(0);

                NodeList textLWSList = ageElement.getChildNodes();
                xmlData[2]= (((Node)textLWSList.item(0)).getNodeValue().trim()).toString();

                //------
            }//end of if clause

    }
    catch(MalformedURLException f){System.err.println(f.getMessage()); }
    catch(NullPointerException npe){
        System.out.println("The Weather Data you searched for is incorrect or does not yet exist, try again. ");
        String s[] = {" ", " "};
        main(s);
    }

   catch (SAXParseException err) {
    System.out.println ("** Parsing error" + ", line " 
         + err.getLineNumber () + ", uri " + err.getSystemId ());
    System.out.println(" " + err.getMessage ());

    }
    catch (SAXException e) {
    Exception x = e.getException ();
    ((x == null) ? e : x).printStackTrace ();

    }catch (Throwable t) {
    t.printStackTrace ();
    }
    return xmlData;
}

Getting tons of null pointers, no matter what I do.

无论我做什么,都会得到大量的空指针。

回答by David Gorsline

When you call .getElementsByTagName(), you need to put a guard on the value you get back:

当您调用 .getElementsByTagName() 时,您需要对返回的值进行保护:

NodeList dateList = firstWeekElement.getElementsByTagName("date");
if (datelist != null) {
    Element dateElement = (Element)dateList.item(0);

et cetera.

等等。

Update

更新

Now that I look at the XML, I see that there are no <date> elements; so that's why dateList is null. You want to be looking for elements like <forecast_information> and <city>.

现在我查看了 XML,我看到没有 <date> 元素;所以这就是 dateList 为空的原因。您想要寻找诸如 <forecast_information> 和 <city> 之类的元素。

NodeList forecasts = firstWeekElement.getElementsByTagName("forecast_information");
if (forecasts != null) {
    Element forecastElement = (Element)forecasts.item(0);