我试图在Postgres db和Groovy中使用JSONB来获取数组中的对象。
我的Json结构如下,存储在我的数据库中。
"playersContainer": {
"players": [
{
"id": "1",
"name": "Nick",
"teamName": "Shire Soldiers",
"ratings": [
1,
5,
6,
9
],
"assists": 17,
"manOfTheMatches": 20,
"cleanSheets": 1,
"data": [
3,
2,
3,
5,
6
],
"totalGoals": 19
},
{
"id": "2",
"name": "Pasty",
"teamName": "Shire Soldiers",
"ratings": [
6,
8,
9,
10
],
"assists": 25,
"manOfTheMatches": 32,
"cleanSheets": 2,
"data": [
3,
5,
7,
9,
10
],
"totalGoals": 24
}
]
}
我想抓住player数组中的对象,循环遍历它们将它们映射到我项目中的对象模型并将它们存储在列表中。
目前我使用此查询:
SELECT content -> 'playersContainer' -> 'players' from site_content
这让我回来了
[{"id": "1", "bio": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla imperdiet lorem tellus, in bibendum sem dignissim sed. Etiam eu elit sit amet lacus accumsan blandit sed ut dolor. Mauris vel dui non nisi vestibulum commodo vel id magna. Donec egestas magna in tincidunt mollis. Fusce mauris arcu, rhoncus ut lacus sed, fermentum ultrices elit. In sollicitudin at ex dapibus vestibulum. Pellentesque congue, est id lobortis viverra, mauris lectus pharetra orci, ut suscipit nisl purus vehicula est. Aliquam suscipit non velit vel feugiat. Quisque nec dictum augue.", "data": [3, 2, 3, 5, 6], "name": "Nick Pocock", "assists": 17, "ratings": [1, 5, 6, 9], "teamName": "Shire Soldiers", "totalGoals": 19, "cleanSheets": 1, "manOfTheMatches": 20}, {"id": "2", "bio": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla imperdiet lorem tellus, in bibendum sem dignissim sed. Etiam eu elit sit amet lacus accumsan blandit sed ut dolor. Mauris vel dui non nisi vestibulum commodo vel id magna. Donec egestas magna in tincidunt mollis. Fusce mauris arcu, rhoncus ut lacus sed, fermentum ultrices elit. In sollicitudin at ex dapibus vestibulum. Pellentesque congue, est id lobortis viverra, mauris lectus pharetra orci, ut suscipit nisl purus vehicula est. Aliquam suscipit non velit vel feugiat. Quisque nec dictum augue.", "data": [3, 5, 7, 9, 10], "name": "Connor Pasty", "assists": 25, "ratings": [6, 8, 9, 10], "teamName": "Shire Soldiers", "totalGoals": 24, "cleanSheets": 2, "manOfTheMatches": 32}]
这给了我一个对象数组但是我只想要里面的对象 然后我想循环遍历对象,映射它们并将它们存储在列表中,就像在Groovy中一样。
Blocking.get {
sql.rows("""
SELECT content -> 'playersContainer' -> 'players' from site_content
""")
}.map { rows ->
rows.collect { GroovyRowResult result ->
objectMapper.readValue(result, Player)
}
}
}
这可以用JSONB吗?
答案 0 :(得分:0)
您可以使用jsonb_array_elements
(read the docs)
SELECT jsonb_array_elements(content->'playersContainer'->'players') FROM site_content