[英]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. 我在AsyncTask<Object,Void,GenericResults>
中使用了此方法,其中GenericResults是一个类,用于存储来自应用程序的许多不同结果,例如当前位置的纬度,经度和压力。 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). 我将在AsyncTask的参数中创建的GenericResults对象传递给它,并使其添加上述值,然后返回修改后的对象(所有这些都在doInBackground中)。
The weather API I'm using is weatherunderground's, located here . 我使用的天气API是位于此处的 weatherunderground。
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. 我遇到的问题有两个:遍历json,如果我告诉它在JsonToken.END_OBJECT
停止JsonToken.END_OBJECT
它只会一直到JSON中的第一个}
,所以它永远不会到达我希望它停止的位置。 On top of that, if I use any fieldName.equals()
inside this method I keep getting null pointer exceptions. 最重要的是,如果我在此方法内使用任何fieldName.equals()
,则将不断获取空指针异常。 What is the correct way to obtain the contents of the pressure_mb
field? 获取pressure_mb
字段内容的正确方法是什么?
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()
在尝试执行任何.equals()
之前,必须稍微解析一下解析器逻辑并确保该值不为null。
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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.