I'm using Groovy to get Json output from an API, and I need to create a few different methods which will access various fields from the Json data structure. I am trying to return the Json object from a method, but I get an error (see code):
public class Weather_api_json {
public static void main(String []args) {
Object weather_bulk = get_data()
println weather_bulk.temp //my "ultimate goal", more or less
}
public static Object get_data() {
def city_name = System.console().readLine 'Enter city name:'
def api_url = "http://api.openweathermap.org/data/2.5/weather?q=$city_name&my_api_key" //not including my api key here
return new groovy.json.JsonSlurper().parseText(new URL(api_url)) // exception thrown (see next line)
// Caught: groovy.lang.MissingMethodException: No signature of method: groovy.json.JsonSlurper.parseText() is applicable for argument types: (URL) values:
}
}
Note that if I instead return a string, a la:
return new groovy.json.JsonSlurper().parseText(new URL(api_url).getText())
then I don't have errors.
Note that this also DOES NOT work, so maybe it's not the "return" that's the problem:
public class Weather_api_json {
public static void main(String []args) {
Object weather_bulk = get_data()
}
public static void get_data() {
def city_name = System.console().readLine 'Enter city name:'
def api_url = "http://api.openweathermap.org/data/2.5/weather?q=$city_name&appid=my_api_key"
def a = new groovy.json.JsonSlurper().parseText(new URL(api_url))
// Caught: groovy.lang.MissingMethodException: No signature of method: groovy.json.JsonSlurper.parseText() is applicable for argument types: (URL) values:
}
}
Any pointers welcome, including general tips or links to learn more. Thank you!