1. 引言
在本文中,我們將描述並提供示例,説明如何在 Groovy 應用程序中使用 JSON。
首先,為了使本文示例能夠正常運行,我們需要設置我們的 pom.xml:
<build>
<plugins>
// ...
<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</build>
<dependencies>
// ...
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>4.0.21</version>
</dependency>
</dependencies>最新版本的 Maven 插件可以在這裏找到:這裏,以及最新版本的 groovy-all 在這裏:這裏。
2. 將 Groovy 對象解析為 JSON
在 Groovy 中將對象轉換為 JSON 非常簡單,假設我們有一個 Account 類:
class Account {
String id
BigDecimal value
Date createdAt
}要將該類的實例轉換為 JSON 字符串,我們需要使用 JsonOutput 類並調用其靜態方法 toJson():
Account account = new Account(
id: '123',
value: 15.6,
createdAt: new SimpleDateFormat('MM/dd/yyyy').parse('01/01/2018')
)
println JsonOutput.toJson(account)因此,我們將會得到解析後的 JSON 字符串:
{"value":15.6,"createdAt":"2018-01-01T02:00:00+0000","id":"123"}2.1. 自定義 JSON 輸出
正如我們所見,日期輸出與我們想要的結果不符。為此,從 2.5 版本開始,groovy.json 包自帶了一套專門的工具。
通過 JsonGenerator 類,我們可以定義 JSON 輸出的選項:
JsonGenerator generator = new JsonGenerator.Options()
.dateFormat('MM/dd/yyyy')
.excludeFieldsByName('value')
.build()
println generator.toJson(account)作為結果,我們將會得到格式化的JSON,其中不包含我們排除的值字段,並且包含格式化的日期:
{"createdAt":"01/01/2018","id":"123"}2.2. 美化 JSON 輸出
使用上述方法,我們瞭解到 JSON 輸出始終以單行形式呈現,如果需要處理更復雜的對象,可能會變得混亂。
但是,我們可以使用 prettyPrint 方法來格式化我們的輸出。
String json = generator.toJson(account)
println JsonOutput.prettyPrint(json)以下是格式化的 JSON 數據:
{
"value": 15.6,
"createdAt": "01/01/2018",
"id": "123"
}3. 將 JSON 解析為 Groovy 對象
我們將使用 Groovy 類 JsonSlurper將 JSON 轉換為 對象。
此外,使用 JsonSlurper,我們擁有大量的重載的 parse方法以及一些特定的方法,例如 parseText、parseFile等。
我們將使用 parseText方法來解析一個 字符串為 Account 類:
def jsonSlurper = new JsonSlurper()
def account = jsonSlurper.parseText('{"id":"123", "value":15.6 }') as Account在上述代碼中,我們有一個方法接收一個 JSON String 並返回一個 Account 對象,該對象可以是任何 Groovy 對象。
此外,我們可以將 JSON String 解析為 Map,無需進行任何類型轉換,並且藉助 Groovy 的動態類型特性,可以獲得與對象相同的效果。
3.1. 解析 JSON 輸入
`JsonSlurper 的默認解析器實現是 JsonParserType.CHAR_BUFFER,但在某些情況下,我們需要處理解析問題。
讓我們來看一個例子:給定一個包含日期屬性的 JSON String,JsonSlurper 將無法正確創建對象,因為它會嘗試將日期解析為 String。`
def jsonSlurper = new JsonSlurper()
def account
= jsonSlurper.parseText('{"id":"123","createdAt":"2018-01-01T02:00:00+0000"}') as Account因此,上述代碼將返回一個包含所有具有null值屬性的Account對象。
為了解決這個問題,我們可以使用JsonParserType.INDEX_OVERLAY。
這樣,它將盡最大努力避免創建String或 char 數組。
def jsonSlurper = new JsonSlurper(type: JsonParserType.INDEX_OVERLAY)
def account
= jsonSlurper.parseText('{"id":"123","createdAt":"2018-01-01T02:00:00+0000"}') as Account現在,上面的代碼將返回一個Account實例,並正確地創建。
3.2. 解析器變體
此外,在 `JsonParserType 中,我們還提供了一些其他實現:
- JsonParserType.LAX 將允許更寬鬆的 JSON 解析,包括支持註釋、不支持引號字符串等。
- JsonParserType.CHARACTER_SOURCE 用於大型文件解析。
4. 結論
我們已經涵蓋了在 Groovy 應用程序中處理 JSON 的內容,並通過一些簡單的示例進行了説明。
有關 groovy.json 包中類的信息,請參閲 Groovy 文檔。