简体   繁体   中英

Can't process weather json in Android correctly using Jackson

I have this method inside an AsyncTask<Object,Void,GenericResults> , with GenericResults being the class where I store a bunch of different results from my application, such as the latitude, longitude and pressure of the current location. I pass the GenericResults object I create in the params of the AsyncTask, and have it add the aforementioned values, then return the modified object (all of this in doInBackground).

The weather API I'm using is weatherunderground's, located here .

The problems I'm having are twofold: just iterating through the json, if I tell it to stop at JsonToken.END_OBJECT it'll only go until the first } in the JSON, so it never gets to where I want it to stop. On top of that, if I use any fieldName.equals() inside this method I keep getting null pointer exceptions. What is the correct way to obtain the contents of the pressure_mb field?

private void getWebPressure(String longitude, String latitude) {
    HttpURLConnection conn;
    try {
        URL weatherUrl = new URL("http://api.wunderground.com/api/"+API_KEY+"/conditions/q/"+latitude+","+longitude+".json");
        conn = (HttpURLConnection) weatherUrl.openConnection();
        InputStream in = new BufferedInputStream(conn.getInputStream());
        JsonFactory factory = new JsonFactory();
        JsonParser parser = factory.createParser(in);
        boolean done = false;
        while (!done) {
            parser.nextToken();
            String fieldName = parser.getCurrentName();
            parser.nextToken();
            Log.v(LOG_TAG, fieldName + " " + parser.getValueAsString());
            if (fieldName.equals("pressure_mb")) {
                done = true;
                result.setPressure(parser.getValueAsString());
            }
        }
        conn.disconnect();
    }
    catch(IOException e){
        Log.e(LOG_TAG,e.toString());
    }
}

Had to switch around the parser logic a bit and make sure the value was not null before trying to do any .equals()

while (parser.nextToken() != null && !done) {
            parser.nextToken();
            String name = parser.getCurrentName();
            if (name!=null){
                if (name.equals("pressure_mb")) {
                    parser.nextToken();
                    String value = parser.getText();
                    Log.v(LOG_TAG,value);
                    result.setPressure(value);
                    break;
                }
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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