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!
CodePudding user response:
Got some help, this worked:
public class Weather_api_json {
public static void main(String []args) {
def weather_bulk = this.get_data()
println weather_bulk.main.temp
}
public static get_data() {
def city_name = "Portland"
def api_url = "http://api.openweathermap.org/data/2.5/weather?q=$city_name&appid=$my_api_key"
def text_response = new URL(api_url).text
def slurper = new groovy.json.JsonSlurper()
def json_response = slurper.parseText(text_response)
return json_response
}
}
CodePudding user response:
Not sure what you are using in groovy to make that API call, I personally use RESTClient, you can also request the content type JSON. The object should already return a JSON that you can navigate with the dot notation.
What you are attempting to do is to transform a URL into a JSON.
try something like:
RESTClient client = new RESTClient()
def path = "full/path/of/the/API"
def response = client.get(path: path, requestContentType : JSON).data
println(response.navigate.the.json)
The documentation is here http://javadox.com/org.codehaus.groovy.modules.http-builder/http-builder/0.6/groovyx/net/http/RESTClient.html
