2011-08-24 62 views
8

JSON正在從RESTful服務讀入,我想打印出來(爲了控制,儘管在.gsp中也可以),用於調試目的。 Groovy 1.3.7(目前截至2011年8月)使用Groovy 1.7.8(它沒有1.8中引入的JsonOutput)可以在Grails 1.3.7中打印JSON嗎?

注意我目前正在閱讀它,我不相信是'grooviest或最可靠的方式來做 - 也許我可以利用轉換器和漂亮的打印,如果做得不同?代碼示例將不勝感激。

def serviceURL = new URL(theURL) 
    def json = new JSONObject(serviceURL.text) 
    println json 

回答

14

您可以用toString(int indentFactor)方法漂亮地打印JSON。例如:

def json = new JSONObject() 
json.put('foo', 'bar') 
json.put('blat', 'greep') 
println json 
===>{"foo":"bar","blat","greep"} 
println json.toString(4) 
===>{ 
    "foo": "bar", 
    "blat": "greep" 
} 
+0

哇,謝謝,很簡單。 – Peter

5

您可以使用grails.converters.JSON(這是JSON最常用的庫):

在你的Config.groovy文件中添加行prettyPrint設置爲true:

grails.converters.default.pretty.print=true 

然後,在你的控制器:

import grails.converters.* 

def serviceURL = new URL(theURL) 
def json = JSON.parse(serviceURL.text) 
println "JSON RESPONSE: ${json.toString()" 
0

除了設置默認Config.groovy漂亮的打印,JSON的toString()方法接受一個布爾參數。它控制着是否打印結果。

import grails.converters.* 
import my.data.* 

def accountJson = Account.get(1001) as JSON 
println(accountJson.toString(true)) 
println(accountJson.toString(false)) 

Grails測試1.3.9。