Reputation: 18130
I don't work with JSON often, but I was having a bit of trouble just doing it in Android with no other libraries. I stumbeled upon Ion by Koush and I'd like to use it to retrieve weather data for London. The JSON api I will be using is from OpenWeather here. As far as I can tell the JSON is valid, so I am now stuck on the Android side of things. My end goal is to have an object/String that reports londons Main > temp
. This is my Android code, but I am unsure of what to do next. Any ideas?
private void getTemperature() {
Log.d(TAG, "2");
final JsonObject json = new JsonObject();
Ion.with(this, "http://api.openweathermap.org/data/2.5/weather?q=London,uk")
.asJsonObject().setCallback(new FutureCallback<JsonObject>() {
@Override
public void onCompleted(Exception e, JsonObject result) {
// do stuff with the result or error
Log.d("TAG", "Complete");
//json = result;
}
});
}
My code gets to the "Complete" log statement, but now I'm trying to set result to my json Object I created, so I un-comment //json = result
, but I get an error in Eclipse. Any help? I would like this method to simply output the Main -> Temp
which (as of right now) is 284.51.
Upvotes: 2
Views: 571
Reputation: 2962
Typical ion usage is aynchronous, but it has synchronous support. Instead of using setCallback (async), use get() (sync) to get it back synchronously. This will block your current Thread though.
final JsonObject json = Ion.with(this, "http://api.openweathermap.org/data/2.5/weather?q=London,uk")
.asJsonObject().
.get();
Upvotes: 8
Reputation: 426
If you want to actually parse the JSON, I'd recommend Googles GSON package
Upvotes: 0
Reputation: 302
Since you marked the json variable as final, I don't think you can reassign it to the point to result in your onCompleted() method.
I would recommend creating an AsyncTask with an HttpClient to actually pull the JSON. I think this would be simpler and cleaner.
HttpClient Example http://www.mkyong.com/java/apache-httpclient-examples/
Upvotes: 0