0

我正在尝试解析具有以下格式的 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
4

2 回答 2

2

在-String\"内部使用''只会"在字符串本身内部(与""-String 相同)。但是你想\"为 JSON 引用(不是 groovy)。所以你需要\\"改用。

除非您真的想使用该字符串进行测试,否则最好只在代码中生成您期望的 JSON。所以你不必为此而战。例如

JsonOutput.toJson([edgeNodeRegistrationStatus: [JsonOutput.toJson([CONFIRMED: "TRUE"])]])
于 2019-05-28T14:23:02.600 回答
1

或者,您可以使用不同的字符串分隔符,因此:

def text = $/{"edgeNodeRegistrationStatus": ["{\"CONFIRMED\":\"TRUE\"}"]}/$

def object = jsonSlurper.parseText(text)

println object.edgeNodeRegistrationStatus[0]
于 2019-05-28T18:30:42.137 回答