使用Groovy解析JSON响应,并根据字符数和其他条件过滤元素



我是Groovy的新手,但用它来从存储在文件中的JSON响应中提取响应。

下面是 JSON 的片段:

"attachments": [
{
"type": "AttachmentText",
"text": "Line 1"
},
{
"type": "AttachmentText",
"text": "This is a different text and can be anything but always > 8 characters"
}
],

我正在尝试根据以下条件获取文本:first case is always < 8字符中的文本而second case is always >8字符中的文本 - 否则没有其他方法可以区分附件元素。但是我的代码只给了我 1 个响应。

{
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText(jsontocsv.toString())
def array1 =  object.attachments
if(array1 != null && !array1.isEmpty())
{
for(def i =0; i<object.attachments.size();i++)
{
if(object.attachments[i].type=="AttachmentText" && object.attachments[i].text.length()>8) {
varaiable1 = RString.of(object.attachments[i].text.toString())
}
else{
variable2 = RString.of("Nothing here")
}
}
}
else {
variable3 = RString.of("No attachments")
}
}

我希望我的variable1会显示响应这是一个不同的文本,可以是任何东西,但总是> 8 个字符,但我在这里一直没有得到任何东西

知道如何解决这个问题吗?

也许是这样的?

def methodReturningLongText()
{
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText(jsontocsv.toString())
def variable1 = RString.of("No attachments")
def array1 =  object.attachments
if(array1)
{
variable1 = RString.of("Nothing here")
for(def i =0; i<array1.size();i++)
{
if(object.attachments[i].type=="AttachmentText" && object.attachments[i].text.length()>8) {
variable1 = RString.of(object.attachments[i].text.toString());
break;
}
}
}
return variable1
}

笔记:

  1. 定义的方法签名
  2. 定义的结果变量 1 具有默认值
  3. if (array1)中使用了时髦真实性测试
  4. 在所有计算返回值的语句中使用相同的结果变量 1
  5. 添加了 break 语句,因此循环将在长值为 发现
  6. 使用默认值并预设"此处无内容"消除了对 else 块的需求。

相关内容

最新更新