我有一段代码调用谷歌地理编码API并返回Json结果,就像这样
def response = new JsonSlurper().parse (url.toURL())
但是返回类型实际上是groovy.json.internal.LazyMap类型。
当我尝试使用以下
打印时 def res = JsonOutput.prettyPrint (response.toString())
我收到这样的错误
Caught: groovy.json.JsonException: Lexing failed on line: 1, column: 2, while reading 'r', no possible valid JSON value or punctuation could be recognized.
groovy.json.JsonException: Lexing failed on line: 1, column: 2, while reading 'r', no possible valid JSON value or punctuation could be recognized.
at org.softwood.Geolocation.Geocoder.completeLatLong(Geocoder.groovy:29)
at org.softwood.Geolocation.Geocoder$completeLatLong.call(Unknown Source)
at org.softwood.Geolocation.TestGeoScript.run(TestGeoScript.groovy:13
懒惰映射上的实际toString()给出了 - 它不会在字符串结果周围放置引号 - 大概是为什么它不能正确解析
{results=[{address_components=[{long_name=South Close, short_name=South Cl, types=[route]}, {long_name=Ipswich, short_name=Ipswich, types=[locality, political]}, {long_name=Ipswich, short_name=Ipswich, types=[postal_town]}, {long_name=Suffolk, short_name=Suffolk, types=[administrative_area_level_2, political]}, {long_name=United Kingdom, short_name=GB, types=[country, political]}, {long_name=IP4 2TH, short_name=IP4 2TH, types=[postal_code]}], formatted_address=South Cl, Ipswich, Suffolk IP4 2TH, UK, geometry={bounds={northeast={lat=52.068566, lng=1.1667458}, southwest={lat=52.0672503, lng=1.1658643}}, location={lat=52.06789149999999, lng=1.1663008}, location_type=GEOMETRIC_CENTER, viewport={northeast={lat=52.0692571302915, lng=1.167654030291502}, southwest={lat=52.0665591697085, lng=1.164956069708498}}}, place_id=ChIJr3u-xXyf2UcRJF_b9Yp2_Ng, types=[route]}, {address_components=[{long_name=IP4 2TH, short_name=IP4 2TH, types=[postal_code]}, {long_name=South Close, short_name=South Cl, types=[route]}, {long_name=Ipswich, short_name=Ipswich, types=[locality, political]}, {long_name=Ipswich, short_name=Ipswich, types=[postal_town]}, {long_name=Suffolk, short_name=Suffolk, types=[administrative_area_level_2, political]}, {long_name=United Kingdom, short_name=GB, types=[country, political]}], formatted_address=South Cl, Ipswich, Suffolk IP4 2TH, UK, geometry={bounds={northeast={lat=52.068475, lng=1.1673588}, southwest={lat=52.0666643, lng=1.1643497}}, location={lat=52.0676263, lng=1.1658643}, location_type=APPROXIMATE, viewport={northeast={lat=52.0689186302915, lng=1.1673588}, southwest={lat=52.0662206697085, lng=1.1643497}}}, place_id=ChIJ7asZ3Xyf2UcRavs18W4IXUM, types=[postal_code]}], status=OK}
查询 - 给出返回的结果 - 如何将其“转换”为一个prettyPrint将解析和呈现的表单?
答案 0 :(得分:6)
使用JsonBuilder似乎是最简单的选择:
String json = new JsonBuilder(response).toPrettyString()
你应该给你漂亮的json吗?
答案 1 :(得分:0)
也可以使用 JsonOutput
:
import groovy.json.JsonOutput;
def json = JsonOutput.toJson([foo: 'bar', baz: [1]])
assert json == '{"foo":"bar","baz":[1]}'
def pretty = JsonOutput.prettyPrint(json)