import com.avoka.component.http.GetRequest
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.utils.URIBuilder
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
CloseableHttpClient client = HttpClients.createDefault();
def uri = new URIBuilder("https://randomuser.me/api/?results=30&nat=US")
HttpGet request = new HttpGet(uri.build())
request.setHeader("content-type", "application/json")
CloseableHttpResponse response = client.execute(request);
String json = EntityUtils.toString(response.getEntity());
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText(json)
def users =[:]
for (int i =0 ; i< object.results.size() ; i++){
def contactJson = object.results[i]
users.gender = contactJson.gender
users.firstname =contactJson.name.first
users.lastname =contactJson.name.last
users.location = contactJson.location.collect { it ->
[Street : it.street,
city : it.city,
state : it.state,
postcode : it.postcode]
}
users.phone =contactJson.phone
users.dateofbirth = contactJson.dob.age
users.nationality =contactJson.nat
}
print users
I am looping the json object and trying to populate the response using maps.
Caught: groovy.lang.MissingPropertyException: No such property: street for class: java.util.LinkedHashMap$Entry
groovy.lang.MissingPropertyException:没有此类属性:类的街道:java.util.LinkedHashMap $ Entry 在post $ _run_closure1.doCall(post.groovy:33) 在post.run(post.groovy:31)
出现此错误,我也得到了打印用户中的一个用户,但列表的大小为30。
答案 0 :(得分:1)
collect
字段上方location
-这不是集合的实例,而是单个Map
users
只是一个地图,您在其中每次迭代都一遍又一遍地覆盖键。一切都可以这么简单:
import groovy.json.JsonSlurper
def slurped = new JsonSlurper().parse(new URL("https://randomuser.me/api/?results=30&nat=US"))
slurped
.results
.collect { u ->
[
gender: u.gender,
firstname: u.name.first,
lastname: u.name.last,
location:[
street: u.location.street,
city: u.location.city,
state: u.location.state,
postcode: u.location.postcode
]
]
}