Groovy中String转Map遇GroovyCastException及ReadyAPI JSON节点操作求助
Hey there! Let's tackle your ReadyAPI Groovy scripting challenges step by step—first handling JSON node extraction and deletion, then fixing that annoying GroovyCastException when converting a String to a Map.
Groovy's built-in JsonSlurper and JsonBuilder are perfect for this in ReadyAPI. Here's a practical example tailored to your workflow:
import groovy.json.JsonSlurper import groovy.json.JsonBuilder // Grab JSON from ReadyAPI response (or any variable you're using) def rawJson = context.response.contentAsString // Replace with your actual JSON source // Parse JSON into a manipulable object (Groovy map/list) def slurper = new JsonSlurper() def jsonPayload = slurper.parseText(rawJson) // Extract a nested node value (e.g., get user's email from a nested contact object) def userEmail = jsonPayload.user.contact.email log.info("Extracted user email: ${userEmail}") // Logs to ReadyAPI's console // Delete a top-level node (e.g., remove unused metadata) jsonPayload.remove('metadata') // Delete a nested node (e.g., remove the phone number from contact) jsonPayload.user.contact.remove('phone') // Convert modified JSON back to a pretty-printed string if you need to reuse it def updatedJson = new JsonBuilder(jsonPayload).toPrettyString() log.info("Modified JSON output: ${updatedJson}")
Quick Notes for ReadyAPI:
- If your JSON is stored in a test case/test suite property, use
context.expand('${#TestCase#YourJsonProperty}')to fetch it correctly (handles escape characters automatically). JsonSlurperreturns dynamic objects that behave like maps/lists, so you can use standard Groovy collection methods on them.
This error almost always happens because either:
- Your string isn't valid JSON (check for missing commas, mismatched brackets, or extra quotes)
- You're trying to cast a JSON array to a Map (or vice versa)
- The string is wrapped in an extra layer of quotes (common when pulling from certain ReadyAPI variables)
Let's cover the most common fixes:
Scenario 1: Extra Quotes Around Your JSON String
If your string looks like "{\"name\":\"ChanChow\"}" (notice the outer quotes), clean it first:
import groovy.json.JsonSlurper def quotedJson = '"{\"name\":\"ChanChow\"}"' // Strip leading/trailing quotes def cleanedJson = quotedJson.replaceAll(/^"|"$/, '') // Parse and convert to Map def jsonMap = slurper.parseText(cleanedJson) as Map
Scenario 2: Confusing JSON Arrays with Objects
If your string is a JSON array (starts with [), you can't cast it to a Map—use a List instead:
def arrayJson = '[{"name":"ChanChow"},{"name":"Alice"}]' def jsonList = new JsonSlurper().parseText(arrayJson) as List
Scenario 3: Compatibility with ReadyAPI's Environment
Sometimes JsonSlurper (the modern version) can cause casting quirks in ReadyAPI. Try using JsonSlurperClassic instead—it returns standard Java collections (HashMap/ArrayList) which are easier to cast:
import groovy.json.JsonSlurperClassic def jsonString = '{"name":"ChanChow","age":30}' def jsonMap = new JsonSlurperClassic().parseText(jsonString) // No need for explicit casting—this returns a HashMap directly
Pro Tip: Validate Your JSON First
If you're unsure why the cast is failing, log the raw string and check its validity with ReadyAPI's built-in JSON viewer (right-click the response > View > JSON) to catch syntax errors.
内容的提问来源于stack exchange,提问作者ChanChow

