【发布时间】:2022-02-04 17:02:16
【问题描述】:
我正在使用 Groovy 从 API 获取 Json 输出,我需要创建一些不同的方法来访问 Json 数据结构中的各个字段。我试图从一个方法返回 Json 对象,但我得到一个错误(见代码):
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:
}
}
请注意,如果我改为返回一个字符串,则为 la:
return new groovy.json.JsonSlurper().parseText(new URL(api_url).getText())
那么我没有错误。
请注意,这也不起作用,所以问题可能不是“返回”:
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:
}
}
欢迎任何指点,包括一般提示或了解更多信息的链接。谢谢!
【问题讨论】:
-
它返回一个 java Map 或 List - 取决于你在 json 响应中的内容。您可以通过分配/删除其中的值来操作此对象,然后在需要时使用
new JsonBuilder(parsedObject).toString()序列化为 json -
感谢@daggett。我从同事那里得到了一些帮助,在下面发布了我自己的答案。
标签: java json api groovy devops