【问题标题】:groovy: convert string (which is a list) to a Groovy Listgroovy:将字符串(这是一个列表)转换为 Groovy 列表
【发布时间】:2020-04-01 15:50:04
【问题描述】:
import groovy.json.JsonSlurper

def ver = "['a', 'b', 'c']"
def jsonSlurper = new JsonSlurper()
def ver_list = jsonSlurper.parseText(ver)
println ver_list

这就是我正在做的。我想遍历ver_list。而且似乎很难找到解决方案。

这是我打印ver_list时的错误:

Caught: groovy.json.JsonException: Unable to determine the current character, it is not a string, number, array, or object

The current character read is ''' with an int value of 39
Unable to determine the current character, it is not a string, number, array, or object
line number 1
index number 1
['a', 'b', 'c']
.^
groovy.json.JsonException: Unable to determine the current character, it is not a string, number, array, or object

The current character read is ''' with an int value of 39
Unable to determine the current character, it is not a string, number, array, or object
line number 1
index number 1
['a', 'b', 'c']

【问题讨论】:

  • 我不确定是什么问题。字符串不是列表,它是列表的文本表示。将其解析为 JSON 后有什么问题?你打印它,我没有看到任何迭代尝试或任何东西。
  • 啊,我没写好。让我编辑问题。
  • 有效的 json 字符串应该用双引号引起来

标签: grails groovy


【解决方案1】:

有效的 json 字符串必须用双引号括起来。

所以在你的代码中改变这一行,它应该可以工作:

def ver = '["a", "b", "c"]'

但是,如果您需要解析无效的 json,您可以尝试 LAX 解析器。

那么即使是下面的字符串也可以被解析

import groovy.json.JsonSlurper
import groovy.json.JsonParserType

def ver = "[a, 'b', 001]"
def jsonSlurper = new JsonSlurper().setType( JsonParserType.LAX )
def ver_list = jsonSlurper.parseText(ver)
println ver_list

【讨论】:

    猜你喜欢
    • 2013-02-14
    • 2015-02-13
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    相关资源
    最近更新 更多