首页 > 解决方案 > 解析 JSON 对象,其值为 JSON 字符串数组

问题描述

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

标签: arraysjsongroovyjsonslurper

解决方案


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

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

JsonOutput.toJson([edgeNodeRegistrationStatus: [JsonOutput.toJson([CONFIRMED: "TRUE"])]])

推荐阅读