YAML support for Apache Groovy - provides YamlBuilder for creating YAML payloads and YamlSlurper for parsing YAML content
npx @tessl/cli install tessl/maven-org-codehaus-groovy--groovy-yaml@3.0.00
# Groovy YAML
1
2
YAML support for Apache Groovy - provides YamlBuilder for creating YAML payloads and YamlSlurper for parsing YAML content. The library offers a fluent API for building YAML documents and comprehensive parsing capabilities for reading YAML from various sources.
3
4
## Package Information
5
6
- **Package Name**: groovy-yaml
7
- **Package Type**: Maven
8
- **Language**: Java/Groovy
9
- **Installation**: Add to Gradle: `implementation 'org.codehaus.groovy:groovy-yaml:3.0.25'`
10
- **Maven**: `<dependency><groupId>org.codehaus.groovy</groupId><artifactId>groovy-yaml</artifactId><version>3.0.25</version></dependency>`
11
12
## Core Imports
13
14
```groovy
15
import groovy.yaml.YamlBuilder
16
import groovy.yaml.YamlSlurper
17
import groovy.yaml.YamlRuntimeException
18
import org.apache.groovy.yaml.util.YamlConverter
19
```
20
21
For Java:
22
23
```java
24
import groovy.yaml.YamlBuilder;
25
import groovy.yaml.YamlSlurper;
26
import groovy.yaml.YamlRuntimeException;
27
import org.apache.groovy.yaml.util.YamlConverter;
28
```
29
30
## Basic Usage
31
32
```groovy
33
// Build YAML using YamlBuilder
34
def builder = new YamlBuilder()
35
builder.person {
36
name "John Doe"
37
age 30
38
address {
39
street "123 Main St"
40
city "Anytown"
41
}
42
}
43
String yamlString = builder.toString()
44
45
// Parse YAML using YamlSlurper
46
def slurper = new YamlSlurper()
47
def parsed = slurper.parseText(yamlString)
48
assert parsed.person.name == "John Doe"
49
assert parsed.person.age == 30
50
```
51
52
## Architecture
53
54
The groovy-yaml library is built around four core components:
55
56
- **YamlBuilder**: Fluent API for constructing YAML documents using Groovy's dynamic features and closures
57
- **YamlSlurper**: Parser for converting YAML content from various sources into native Groovy data structures
58
- **YamlConverter**: Internal utility for bidirectional conversion between YAML and JSON formats
59
- **YamlRuntimeException**: Custom exception type for YAML processing errors
60
61
Internally, the library leverages Jackson's YAML dataformat libraries and converts between JSON and YAML formats, allowing seamless integration with Groovy's existing JsonBuilder and JsonSlurper components.
62
63
## Capabilities
64
65
### YAML Building
66
67
Construct YAML documents using various builder patterns including named arguments, closures, arrays, and collections.
68
69
```groovy { .api }
70
class YamlBuilder extends GroovyObjectSupport implements Writable {
71
/** Default constructor */
72
YamlBuilder()
73
74
/** Get the internal content object */
75
Object getContent()
76
77
/** Create root YAML object from named arguments */
78
Object call(Map m)
79
80
/** Create root YAML array from list */
81
Object call(List l)
82
83
/** Create root YAML array from varargs */
84
Object call(Object... args)
85
86
/** Create root YAML array applying closure to collection */
87
Object call(Iterable coll, Closure c)
88
Object call(Collection coll, Closure c)
89
90
/** Create root YAML object from closure */
91
Object call(Closure c)
92
93
/** Dynamic method dispatch for builder DSL */
94
Object invokeMethod(String name, Object args)
95
96
/** Serialize internal structure to YAML string */
97
String toString()
98
99
/** Write YAML output to Writer */
100
Writer writeTo(Writer out) throws IOException
101
}
102
```
103
104
**Usage Examples:**
105
106
```groovy
107
// Named arguments approach
108
def builder = new YamlBuilder()
109
builder.person(name: "Alice", age: 25)
110
111
// Closure-based DSL
112
builder.person {
113
name "Bob"
114
age 30
115
hobbies(["reading", "swimming"])
116
}
117
118
// Array creation
119
builder([1, 2, 3, 4])
120
121
// Collection with closure
122
def people = [new Person(name: "Charlie"), new Person(name: "Diana")]
123
builder people, { person ->
124
name person.name
125
id person.id
126
}
127
```
128
129
### YAML Parsing
130
131
Parse YAML content from strings, readers, streams, files, or paths into native Groovy data structures.
132
133
```groovy { .api }
134
class YamlSlurper {
135
/** Default constructor */
136
YamlSlurper()
137
138
/** Parse YAML string into object tree */
139
Object parseText(String yaml)
140
141
/** Parse YAML from Reader into object tree */
142
Object parse(Reader reader)
143
144
/** Parse YAML from InputStream into object tree */
145
Object parse(InputStream stream)
146
147
/** Parse YAML from File into object tree */
148
Object parse(java.io.File file) throws IOException
149
150
/** Parse YAML from Path into object tree */
151
Object parse(Path path) throws IOException
152
}
153
```
154
155
**Usage Examples:**
156
157
```groovy
158
def slurper = new YamlSlurper()
159
160
// Parse from string
161
def result1 = slurper.parseText("""
162
name: "Product X"
163
price: 29.99
164
categories:
165
- electronics
166
- gadgets
167
""")
168
169
// Parse from file
170
def result2 = slurper.parse(new File("config.yml"))
171
172
// Parse from path
173
def result3 = slurper.parse(Paths.get("data.yml"))
174
175
// Parse from input stream
176
def result4 = slurper.parse(new FileInputStream("input.yml"))
177
```
178
179
### YAML/JSON Conversion
180
181
Utility functions for converting between YAML and JSON formats.
182
183
```groovy { .api }
184
class YamlConverter {
185
/** Convert YAML reader content to JSON string */
186
static String convertYamlToJson(Reader yamlReader)
187
188
/** Convert JSON reader content to YAML string */
189
static String convertJsonToYaml(Reader jsonReader)
190
}
191
```
192
193
**Usage Examples:**
194
195
```groovy
196
// Convert YAML to JSON
197
String yamlContent = "name: John\nage: 30"
198
String jsonResult = YamlConverter.convertYamlToJson(new StringReader(yamlContent))
199
200
// Convert JSON to YAML
201
String jsonContent = '{"name":"John","age":30}'
202
String yamlResult = YamlConverter.convertJsonToYaml(new StringReader(jsonContent))
203
```
204
205
### Exception Handling
206
207
Custom exception type for YAML processing errors.
208
209
```groovy { .api }
210
class YamlRuntimeException extends GroovyRuntimeException {
211
/** Exception with message */
212
YamlRuntimeException(String msg)
213
214
/** Exception with cause */
215
YamlRuntimeException(Throwable cause)
216
217
/** Exception with message and cause */
218
YamlRuntimeException(String msg, Throwable cause)
219
}
220
```
221
222
**Common Error Scenarios:**
223
224
```groovy
225
try {
226
def slurper = new YamlSlurper()
227
def result = slurper.parseText("invalid: yaml: content:")
228
} catch (YamlRuntimeException e) {
229
println "YAML parsing failed: ${e.message}"
230
}
231
```
232
233
## Types
234
235
```groovy { .api }
236
// Standard Java/Groovy types used throughout the API
237
interface Writable {
238
Writer writeTo(Writer out) throws IOException
239
}
240
241
class GroovyObjectSupport {
242
// Base class providing dynamic method invocation
243
}
244
245
class GroovyRuntimeException extends RuntimeException {
246
// Base exception class for Groovy runtime errors
247
}
248
249
// Java standard library types
250
class Reader // java.io.Reader
251
class Writer // java.io.Writer
252
class InputStream // java.io.InputStream
253
class File // java.io.File
254
class Path // java.nio.file.Path
255
interface Map<K,V> // java.util.Map
256
interface List<E> // java.util.List
257
interface Collection<E> // java.util.Collection
258
interface Iterable<T> // java.lang.Iterable
259
class Closure<V> // groovy.lang.Closure
260
```