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

使用Groovy解析多个JSON对象的技术咨询

使用Groovy解析多个JSON对象(含不完整响应处理)

嘿,我来帮你搞定Groovy解析JSON的问题,不管是完整的商品数据,还是那种半截的截断响应,都有对应的处理方式~

1. 解析完整的单个JSON对象

Groovy自带的JsonSlurper真的是处理JSON的神器,上手超简单,不用额外引入依赖。针对你给出的完整商品JSON,我们可以这么解析:

先把JSON字符串准备好(也可以直接从HTTP响应流里读取):

def jsonStr = '''{ "id":27, "merchant_id":"39", "title":"Shorts", "subtitle":null, "price":100, "description":null, "images":[ ], "image_thumbs":[ ], "options":[ { "code":"size", "label":"Size", "extra_info":"", "values":[ { "label":"Small", "value":"4" }, { "label":"Medium", "value":"5" } ] } ], "options_available":[ { "combination":[ { "code":"size", "value":"Small" } ] }, { "combination":[ { "code":"size", "value":"Medium" } ] } ], "custom_options":[ ] }'''

// 初始化JsonSlurper
def slurper = new groovy.json.JsonSlurper()
def product = slurper.parseText(jsonStr)

// 轻松获取各种字段,包括嵌套结构
println "商品标题: ${product.title}"
println "售价: ${product.price}元"
// 遍历尺码选项
product.options.each { option ->
    println "\n${option.label}选项:"
    option.values.each { size ->
        println "- ${size.label} (对应值: ${size.value})"
    }
}

运行这段代码,就能拿到所有你需要的字段,嵌套的数组和对象也能轻松遍历。

2. 处理不完整/截断的JSON响应

如果遇到像{ "id"...}这种截断的不完整JSON,直接用JsonSlurper解析会报错,毕竟格式不合法。这里给你两种实用思路:

2.1 尝试补全JSON(适用于已知结构的场景)

如果你对响应的结构有预期,可以手动补全语法错误的部分,比如:

def incompleteJson = '''{ "id"...}'''
// 简单修复:替换省略号,补全必要字段和闭合括号
def fixedJson = incompleteJson.replace('...', ':29, "merchant_id":"50", "title":"Hat" }')
def slurper = new groovy.json.JsonSlurper()
def partialProduct = slurper.parseText(fixedJson)
println "获取到的商品ID: ${partialProduct.id}"

这种方法适合你大概知道缺失内容的情况,灵活性稍差,但胜在简单直接。

2.2 流式解析+错误捕获(处理连续的多对象响应)

如果你的响应是多个JSON对象连续输出(比如没有分隔符,或者每行一个),其中最后一个对象可能截断,这时候可以用流式解析配合try-catch跳过无效对象:

// 模拟包含不完整对象的响应流
def jsonStream = new ByteArrayInputStream('{"id":27, "title":"Shorts"}{"id":28, "title":"T-Shirt"}{"id":29...}'.getBytes())
def slurper = new groovy.json.JsonSlurper()

try {
    def parser = slurper.parse(jsonStream, 'UTF-8')
    parser.each { obj ->
        println "商品ID: ${obj.id}"
    }
} catch (groovy.json.JsonException e) {
    println "遇到无效的截断JSON,已自动跳过: ${e.message}"
}

这样既可以处理正常的JSON对象,又能捕获最后一个不完整对象的错误,不会导致整个解析流程崩溃。

3. 批量解析多个独立的JSON对象

如果你的需求是解析多个JSON对象(不管是数组包裹还是换行分隔的形式),处理起来也很轻松:

3.1 数组形式的多对象

如果JSON是数组结构(比如[{"id":27...}, {"id":28...}]),直接解析成列表即可:

def arrayJson = '''[{"id":27, "title":"Shorts"}, {"id":28, "title":"T-Shirt"}, {"id":29, "title":"Hat"}]'''
def slurper = new groovy.json.JsonSlurper()
def products = slurper.parseText(arrayJson)

products.each { product ->
    println "商品: ${product.title} (ID: ${product.id})"
}

3.2 换行分隔的多对象

如果是每行一个JSON对象的格式,按行拆分后逐个解析就行:

def multiJsonStr = '''{"id":27, "title":"Shorts"}
{"id":28, "title":"T-Shirt"}
{"id":29, "title":"Hat"}'''

def slurper = new groovy.json.JsonSlurper()
multiJsonStr.split('\n').each { line ->
    if (line.trim()) { // 跳过空行
        def product = slurper.parseText(line)
        println "ID: ${product.id}, 标题: ${product.title}"
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:46:34