我正在尝试解析以下格式的JSON字符串
{"edgeNodeRegistrationStatus": ["{\"CONFIRMED\":\"TRUE\"}"]}
我写了一个代码来解析它。
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText('{"edgeNodeRegistrationStatus": ["{\"CONFIRMED\":\"TRUE\"}"]}')
println(object["edgeNodeRegistrationStatus"][0])
我希望代码可以打印{"CONFIRMED":"TRUE"}
。但是它抛出了错误
Caught: groovy.json.JsonException: expecting a ',' or a ']', but got
the current character of 'C' with an int value of 67 on array index of 1
The current character read is 'C' with an int value of 67
expecting a ',' or a ']', but got
the current character of 'C' with an int value of 67 on array index of 1
line number 1
index number 35
{"edgeNodeRegistrationStatus": ["{"CONFIRMED":"TRUE"}"]}
...................................^
groovy.json.JsonException: expecting a ',' or a ']', but got
the current character of 'C' with an int value of 67 on array index of 1
The current character read is 'C' with an int value of 67
expecting a ',' or a ']', but got
the current character of 'C' with an int value of 67 on array index of 1
line number 1
index number 35
{"edgeNodeRegistrationStatus": ["{"CONFIRMED":"TRUE"}"]}
...................................^
at jdoodle.run(jdoodle.groovy:4)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
Command exited with non-zero status 1
答案 0 :(得分:2)
在\"
字符串中使用''
只会在字符串本身内部提供"
(与""
字符串相同)。但是,您想引用JSON的\"
(不是俗套的)。因此,您需要改用\\"
。
除非您真的想使用该字符串进行测试,否则最好只在代码中生成期望的JSON。因此,您不必为此而战。例如
JsonOutput.toJson([edgeNodeRegistrationStatus: [JsonOutput.toJson([CONFIRMED: "TRUE"])]])
答案 1 :(得分:1)
或者,您可以使用不同的String分隔符:
def text = $/{"edgeNodeRegistrationStatus": ["{\"CONFIRMED\":\"TRUE\"}"]}/$
def object = jsonSlurper.parseText(text)
println object.edgeNodeRegistrationStatus[0]