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

使用Groovy获取JsonSlurper属性的技术问询(附示例JSON)

用Groovy的JsonSlurper解析指定JSON并获取属性

嘿,这事儿不难,我来带你一步步用Groovy自带的JsonSlurper搞定这个JSON的属性读取~

1. 先明确你的JSON结构

先把你给的JSON结构理清楚,方便后续定位属性:

{ 
  "type" : "record", 
  "name" : "test", 
  "fields" : [ 
    { 
      "name" : "y", 
      "type" : { 
        "type" : "array", 
        "items" : "double" 
      }, 
      "doc" : "Type inferred from '[1.0,0.9766205557100867,0.907575419670957,0.7960930657056438,0.6473862847818277,0.46840844069979015,0.26752833852922075,0.05413890858541761,-0.16178199655276473,-0.37013815533991445,-0.5611870653623823,-0.7259954919231308,-0.8568571761675893,-0.9476531711828025,-0.9941379571543596,-0.9941379571543596,-0.9476531711828025,...'" 
    } 
  ] 
}

2. 两种常见场景的代码实现

场景一:JSON是字符串形式

如果你的JSON已经是字符串了,直接用parseText解析就行:

import groovy.json.JsonSlurper

// 把你的JSON内容放到字符串里
def jsonString = '''{ 
  "type" : "record", 
  "name" : "test", 
  "fields" : [ 
    { 
      "name" : "y", 
      "type" : { 
        "type" : "array", 
        "items" : "double" 
      }, 
      "doc" : "Type inferred from '[1.0,0.9766205557100867,0.907575419670957,0.7960930657056438,0.6473862847818277,0.46840844069979015,0.26752833852922075,0.05413890858541761,-0.16178199655276473,-0.37013815533991445,-0.5611870653623823,-0.7259954919231308,-0.8568571761675893,-0.9476531711828025,-0.9941379571543596,-0.9941379571543596,-0.9476531711828025,...'" 
    } 
  ] 
}'''

// 初始化JsonSlurper
def slurper = new JsonSlurper()
// 解析字符串得到Groovy对象
def jsonData = slurper.parseText(jsonString)

// 读取顶层属性
def recordType = jsonData.type
def recordName = jsonData.name
println "顶层类型: $recordType, 名称: $recordName"

// 读取fields数组里第一个字段的属性
def firstField = jsonData.fields[0]
def fieldName = firstField.name
def fieldDoc = firstField.doc
println "字段名称: $fieldName, 字段描述: $fieldDoc"

// 读取嵌套的type属性
def fieldType = firstField.type.type
def fieldItems = firstField.type.items
println "字段的类型: $fieldType, 数组元素类型: $fieldItems"

场景二:JSON存放在文件里

如果你的JSON是本地文件,把parseText换成parse方法,传入文件路径就行:

import groovy.json.JsonSlurper
import java.io.File

// 替换成你的JSON文件路径
def jsonFile = new File("your/json/file/path.json")
def slurper = new JsonSlurper()
def jsonData = slurper.parse(jsonFile)

// 下面的属性读取和场景一完全一样
def recordType = jsonData.type
// ... 其他属性读取代码

3. 几个实用小技巧

  • JsonSlurper解析后返回的是Groovy的Map和List组合对象,所以可以直接用点.或者下标[]访问属性,非常灵活
  • 如果fields里有多个字段,可以用循环遍历:jsonData.fields.each { field -> println field.name }
  • 怕空指针的话,用Groovy的安全导航操作符?.,比如jsonData?.fields?.getAt(0)?.name,就算某个层级为空也不会报错

内容的提问来源于stack exchange,提问作者amira khalifa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:40:13