如何在Groovy中正确解析嵌套JSON并获取userId?
userId的几种实用方法 Hey there! Let's break down how to grab that userId field from nested JSON in Groovy—no need to force classes or stick strictly to JsonSlurper if you don't want to. Let's start with the most straightforward approaches.
方法1:用JsonSlurper(最常用且靠谱)
Groovy的JsonSlurper parses JSON into native Groovy collections (Maps and Lists), and its GPath syntax makes accessing nested fields super intuitive—way cleaner than chaining key lookups like in some other languages.
基础嵌套JSON示例
假设你的待解析JSON长这样:
{ "apiResponse": { "userData": { "profile": { "userId": "benihana_123", "displayName": "Benihana" }, "preferences": { "theme": "dark" } } } }
对应的Groovy代码:
import groovy.json.JsonSlurper // 解析JSON字符串(也可以直接解析文件,看你的数据源) def jsonString = '''{ "apiResponse": { "userData": { "profile": { "userId": "benihana_123", "displayName": "Benihana" } } } }''' def slurper = new JsonSlurper() def parsedJson = slurper.parseText(jsonString) // 直接链式访问嵌套的userId字段 def userId = parsedJson.apiResponse.userData.profile.userId println "Found User ID: $userId" // 输出 Found User ID: benihana_123 // 安全访问(避免空指针,如果某个层级可能不存在) def safeUserId = parsedJson?.apiResponse?.userData?.profile?.userId
如果JSON包含数组
如果你的数据是数组嵌套结构,比如多个用户条目:
{ "userList": [ {"profile": {"userId": "user_001"}}, {"profile": {"userId": "user_002"}}, {"profile": {"userId": "user_003"}} ] }
Groovy会帮你自动扁平化数组,轻松获取所有userId:
def arrayJson = '''{ "userList": [ {"profile": {"userId": "user_001"}}, {"profile": {"userId": "user_002"}}, {"profile": {"userId": "user_003"}} ] }''' def parsedArray = slurper.parseText(arrayJson) // 一次性拿到所有userId的列表 def allUserIds = parsedArray.userList.profile.userId println "All User IDs: $allUserIds" // 输出 All User IDs: [user_001, user_002, user_003] // 遍历数组逐个获取 parsedArray.userList.each { userItem -> println "Individual User ID: ${userItem.profile.userId}" }
方法2:不依赖JsonSlurper?试试Groovy的简化写法
If you want to skip JsonSlurper entirely (though I don't recommend this for production due to security risks), you can use Eval.me to convert the JSON string directly to a Groovy Map. Only use this if you fully trust the JSON source—it executes code under the hood.
def jsonString = '''{"data": {"user": {"userId": "benihana_456"}}}''' def jsonMap = Eval.me("[" + jsonString + "]")[0] def userId = jsonMap.data.user.userId println userId // 输出 benihana_456
对比你的Python实现
假设你的Python代码 looks like this:
import json with open('user_data.json') as f: json_data = json.load(f) user_id = json_data['apiResponse']['userData']['profile']['userId']
The Groovy equivalent is even more concise, especially when reading from a file:
import groovy.json.JsonSlurper def jsonFile = new File('user_data.json') def parsedJson = new JsonSlurper().parse(jsonFile) def userId = parsedJson.apiResponse.userData.profile.userId
No need for bracket notation—just chain the fields with . thanks to GPath!
内容的提问来源于stack exchange,提问作者Benihana

