0
# Hjson and JSON Parsing
1
2
Comprehensive parsing capabilities for both Hjson (Human JSON) and standard JSON formats with error handling, encoding support, and configurable options.
3
4
## Capabilities
5
6
### Parse Hjson from String
7
8
Parse Hjson text directly from a string with automatic format detection and error reporting.
9
10
```java { .api }
11
/**
12
* Reads a Hjson value from the given string
13
* @param text the string that contains the Hjson value
14
* @return the JsonValue that has been read
15
* @throws ParseException if the input is not valid Hjson
16
*/
17
static JsonValue readHjson(String text);
18
```
19
20
**Usage Examples:**
21
22
```java
23
import org.hjson.JsonValue;
24
import org.hjson.JsonObject;
25
26
// Parse Hjson with comments and unquoted strings
27
JsonValue value = JsonValue.readHjson("""
28
{
29
// Configuration for the application
30
name: My Application
31
version: "1.0.0"
32
debug: true
33
servers: [
34
localhost:8080
35
prod.example.com
36
]
37
}
38
""");
39
40
JsonObject config = value.asObject();
41
String name = config.getString("name", "");
42
boolean debug = config.getBoolean("debug", false);
43
```
44
45
### Parse Hjson from Reader
46
47
Parse Hjson from any Reader (file, stream, etc.) with automatic buffering for optimal performance.
48
49
```java { .api }
50
/**
51
* Reads a Hjson value from the given reader
52
* Characters are read in chunks and buffered internally, therefore wrapping an existing reader in
53
* an additional BufferedReader does not improve reading performance
54
* @param reader the reader to read the Hjson value from
55
* @return the JsonValue that has been read
56
* @throws IOException if an I/O error occurs in the reader
57
* @throws ParseException if the input is not valid Hjson
58
*/
59
static JsonValue readHjson(Reader reader) throws IOException;
60
```
61
62
**Usage Examples:**
63
64
```java
65
import org.hjson.JsonValue;
66
import java.io.FileReader;
67
import java.io.IOException;
68
69
// Parse from file
70
try (FileReader reader = new FileReader("config.hjson")) {
71
JsonValue config = JsonValue.readHjson(reader);
72
// Process configuration...
73
} catch (IOException e) {
74
System.err.println("Failed to read file: " + e.getMessage());
75
} catch (ParseException e) {
76
System.err.println("Invalid Hjson at line " + e.getLine() +
77
", column " + e.getColumn() + ": " + e.getMessage());
78
}
79
80
// Parse from any Reader
81
StringReader stringReader = new StringReader("{ name: test, value: 42 }");
82
JsonValue result = JsonValue.readHjson(stringReader);
83
```
84
85
### Parse Hjson with Options
86
87
Parse Hjson with custom configuration options for specialized parsing behavior.
88
89
```java { .api }
90
/**
91
* Reads a Hjson value from the given string with custom options
92
* @param text the string that contains the Hjson value
93
* @param options the Hjson parsing options
94
* @return the JsonValue that has been read
95
* @throws ParseException if the input is not valid Hjson
96
*/
97
static JsonValue readHjson(String text, HjsonOptions options);
98
99
/**
100
* Reads a Hjson value from the given reader with custom options
101
* @param reader the reader to read the Hjson value from
102
* @param options the Hjson parsing options
103
* @return the JsonValue that has been read
104
* @throws IOException if an I/O error occurs in the reader
105
* @throws ParseException if the input is not valid Hjson
106
*/
107
static JsonValue readHjson(Reader reader, HjsonOptions options) throws IOException;
108
```
109
110
**Usage Examples:**
111
112
```java
113
import org.hjson.JsonValue;
114
import org.hjson.HjsonOptions;
115
import org.hjson.HjsonDsf;
116
117
// Configure options for specialized parsing
118
HjsonOptions options = new HjsonOptions();
119
options.setDsfProviders(new IHjsonDsfProvider[] {
120
HjsonDsf.math(), // Support Inf, -Inf, NaN, -0
121
HjsonDsf.hex(true) // Support 0x prefixed hex numbers
122
});
123
options.setParseLegacyRoot(true); // Allow root objects without braces
124
125
// Parse with math DSF support
126
JsonValue mathResult = JsonValue.readHjson("""
127
{
128
infinity: +Inf
129
notANumber: NaN
130
hexValue: 0xFF
131
}
132
""", options);
133
134
// Parse legacy format (object without root braces)
135
JsonValue legacyResult = JsonValue.readHjson("""
136
name: Legacy Config
137
port: 8080
138
enabled: true
139
""", options);
140
```
141
142
### Parse Standard JSON from String
143
144
Parse standard JSON text with strict validation and comprehensive error reporting.
145
146
```java { .api }
147
/**
148
* Reads a JSON value from the given string
149
* @param text the string that contains the JSON value
150
* @return the JsonValue that has been read
151
* @throws ParseException if the input is not valid JSON
152
*/
153
static JsonValue readJSON(String text);
154
```
155
156
**Usage Examples:**
157
158
```java
159
import org.hjson.JsonValue;
160
import org.hjson.JsonArray;
161
162
// Parse standard JSON
163
JsonValue value = JsonValue.readJSON("""
164
{
165
"name": "Standard JSON",
166
"version": "1.0.0",
167
"features": ["parsing", "validation", "serialization"]
168
}
169
""");
170
171
JsonArray features = value.asObject().get("features").asArray();
172
System.out.println("Feature count: " + features.size());
173
```
174
175
### Parse Standard JSON from Reader
176
177
Parse standard JSON from any Reader with automatic buffering and encoding detection.
178
179
```java { .api }
180
/**
181
* Reads a JSON value from the given reader
182
* Characters are read in chunks and buffered internally, therefore wrapping an existing reader in
183
* an additional BufferedReader does not improve reading performance
184
* @param reader the reader to read the JSON value from
185
* @return the JsonValue that has been read
186
* @throws IOException if an I/O error occurs in the reader
187
* @throws ParseException if the input is not valid JSON
188
*/
189
static JsonValue readJSON(Reader reader) throws IOException;
190
```
191
192
**Usage Examples:**
193
194
```java
195
import org.hjson.JsonValue;
196
import java.io.FileReader;
197
import java.net.URL;
198
import java.io.InputStreamReader;
199
200
// Parse JSON from file
201
try (FileReader reader = new FileReader("data.json")) {
202
JsonValue data = JsonValue.readJSON(reader);
203
// Process data...
204
}
205
206
// Parse JSON from URL
207
URL url = new URL("https://api.example.com/data.json");
208
try (InputStreamReader reader = new InputStreamReader(url.openStream())) {
209
JsonValue apiData = JsonValue.readJSON(reader);
210
// Process API response...
211
}
212
```
213
214
## Error Handling
215
216
All parsing methods throw `ParseException` for invalid input, providing detailed error information:
217
218
```java { .api }
219
class ParseException extends RuntimeException {
220
/**
221
* Gets the character offset where the error occurred
222
* @return the character offset (0-based)
223
*/
224
int getOffset();
225
226
/**
227
* Gets the line number where the error occurred
228
* @return the line number (1-based)
229
*/
230
int getLine();
231
232
/**
233
* Gets the column number where the error occurred
234
* @return the column number (1-based)
235
*/
236
int getColumn();
237
}
238
```
239
240
**Error Handling Examples:**
241
242
```java
243
try {
244
JsonValue invalid = JsonValue.readHjson("{ name: unclosed");
245
} catch (ParseException e) {
246
System.err.printf("Parse error at line %d, column %d (offset %d): %s%n",
247
e.getLine(), e.getColumn(), e.getOffset(), e.getMessage());
248
// Output: Parse error at line 1, column 15 (offset 14): Expected '}'
249
}
250
251
try {
252
JsonValue invalidJson = JsonValue.readJSON("{ 'single-quotes': 'not allowed' }");
253
} catch (ParseException e) {
254
System.err.println("Invalid JSON: " + e.getMessage());
255
// Output: Invalid JSON: Expected '"' at line 1, column 3
256
}
257
```
258
259
## Configuration Options
260
261
### HjsonOptions
262
263
Configure parsing behavior for Hjson input:
264
265
```java { .api }
266
class HjsonOptions {
267
/**
268
* Creates default Hjson parsing options
269
*/
270
HjsonOptions();
271
272
/**
273
* Gets the array of Domain Specific Format providers
274
* @return array of DSF providers (may be null)
275
*/
276
IHjsonDsfProvider[] getDsfProviders();
277
278
/**
279
* Sets the Domain Specific Format providers for specialized value parsing
280
* @param providers array of DSF providers
281
*/
282
void setDsfProviders(IHjsonDsfProvider[] providers);
283
284
/**
285
* Gets whether to parse legacy root format (object without braces)
286
* @return true if legacy root parsing is enabled
287
*/
288
boolean getParseLegacyRoot();
289
290
/**
291
* Sets whether to parse legacy root format (object without braces)
292
* @param value true to enable legacy root parsing
293
*/
294
void setParseLegacyRoot(boolean value);
295
}
296
```
297
298
### Domain Specific Formats
299
300
Use built-in DSF providers for specialized value parsing:
301
302
```java { .api }
303
class HjsonDsf {
304
/**
305
* Returns math DSF provider supporting mathematical constants
306
* Supports: +Inf, -Inf, Inf, +NaN, NaN, -NaN, -0
307
* @return math DSF provider
308
*/
309
static IHjsonDsfProvider math();
310
311
/**
312
* Returns hex DSF provider supporting hexadecimal numbers
313
* Supports: 0x prefixed hexadecimal numbers (e.g., 0xFF, 0x123)
314
* @param stringify whether to stringify numbers back to hex format
315
* @return hex DSF provider
316
*/
317
static IHjsonDsfProvider hex(boolean stringify);
318
}
319
```
320
321
### Global EOL Configuration
322
323
Configure the end-of-line character(s) used globally for JSON/Hjson output formatting.
324
325
```java { .api }
326
/**
327
* Gets the current end-of-line character(s) used for output formatting
328
* @return the EOL string (default is system line separator)
329
*/
330
static String getEol();
331
332
/**
333
* Sets the end-of-line character(s) used for output formatting
334
* @param value the EOL string to use (e.g., "\n", "\r\n", "\r")
335
*/
336
static void setEol(String value);
337
```
338
339
**Usage Examples:**
340
341
```java
342
import org.hjson.JsonValue;
343
import org.hjson.JsonObject;
344
import org.hjson.Stringify;
345
346
// Check current EOL setting
347
String currentEol = JsonValue.getEol();
348
System.out.println("Current EOL: " + currentEol.replace("\n", "\\n").replace("\r", "\\r"));
349
350
// Set Unix-style line endings
351
JsonValue.setEol("\n");
352
353
// Set Windows-style line endings
354
JsonValue.setEol("\r\n");
355
356
// Create formatted JSON with configured EOL
357
JsonObject obj = new JsonObject()
358
.add("name", "Test")
359
.add("value", 42);
360
361
String formatted = obj.toString(Stringify.FORMATTED);
362
System.out.println("Formatted with custom EOL:");
363
System.out.println(formatted);
364
365
// Reset to system default
366
JsonValue.setEol(System.lineSeparator());
367
```
368
369
## Performance Considerations
370
371
- **Buffering**: Both string and Reader parsing use internal buffering for optimal performance
372
- **Memory**: String parsing loads the entire input into memory; use Reader for large files
373
- **Encoding**: Reader-based parsing respects the Reader's character encoding
374
- **Reuse**: JsonValue instances are immutable and can be safely shared across threads
375
- **Error Position**: ParseException provides precise error location for debugging