Groovy JsonSlurper and nested maps

霸气de小男生 提交于 2019-12-08 11:02:09

问题


I have a method that returns fairly-nested JSON such as:

[[fizz: buzz, foos: [[count: 4, flim: flam], [count: 6, flim: flume]]]]

When I try to use JsonSlurper to slurp this JSON into a def result I am getting exceptions:

// json == “[[fizz: buzz, foos: [[count: 4, flim: flam], [count: 6, flim: flume]]]]"
String json = getJSON()
JsonSlurper slurper = new JsonSlurper()

def result = slurper.parseText(json)

Produces an exception thrown when parseText executes:

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

Any ideas what the fix is?


回答1:


I think you're trying to use Groovy's map notation as JSON. JSON uses curlies for maps, like this

import groovy.json.*

def obj = [["fizz": "buzz", "foos": [["count": 4, "flim": "flam"], ["count": 6, "flim": "flume"]]]]
def json = JsonOutput.toJson(obj)
assert json == '''[{"fizz":"buzz","foos":[{"count":4,"flim":"flam"},{"count":6,"flim":"flume"}]}]'''
def result = new JsonSlurper().parseText(json)


来源:https://stackoverflow.com/questions/32231974/groovy-jsonslurper-and-nested-maps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!