You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.

1. JSON Processing: Extract Node Values & Delete Specific Nodes

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).
  • JsonSlurper returns dynamic objects that behave like maps/lists, so you can use standard Groovy collection methods on them.
2. Fixing GroovyCastException When Converting String to Map

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:45:26