0
# Configuration and Options
1
2
Configuration system providing control over JSON parsing, mapping, options, and evaluation behavior. The Configuration class is immutable and uses a builder pattern for creating customized configurations.
3
4
## Capabilities
5
6
### Configuration Management
7
8
Core configuration class and factory methods for creating configurations.
9
10
```java { .api }
11
/**
12
* Immutable configuration object for JsonPath operations
13
*/
14
public class Configuration {
15
/**
16
* Creates a configuration based on default values
17
* @return New configuration with defaults
18
*/
19
public static Configuration defaultConfiguration();
20
21
/**
22
* Returns a new ConfigurationBuilder
23
* @return Builder instance for configuration creation
24
*/
25
public static ConfigurationBuilder builder();
26
27
/**
28
* Sets default configuration for the library
29
* @param defaults Default configuration settings
30
*/
31
public static synchronized void setDefaults(Defaults defaults);
32
}
33
```
34
35
**Usage Examples:**
36
37
```java
38
import com.jayway.jsonpath.Configuration;
39
import com.jayway.jsonpath.Option;
40
41
// Use default configuration
42
Configuration defaultConfig = Configuration.defaultConfiguration();
43
44
// Build custom configuration
45
Configuration customConfig = Configuration.builder()
46
.options(Option.SUPPRESS_EXCEPTIONS, Option.ALWAYS_RETURN_LIST)
47
.build();
48
```
49
50
### Configuration Properties
51
52
Methods for accessing and modifying configuration properties.
53
54
```java { .api }
55
/**
56
* Returns the JsonProvider used by this configuration
57
* @return JsonProvider instance
58
*/
59
public JsonProvider jsonProvider();
60
61
/**
62
* Creates new configuration with different JsonProvider
63
* @param newJsonProvider JsonProvider to use
64
* @return New configuration instance
65
*/
66
public Configuration jsonProvider(JsonProvider newJsonProvider);
67
68
/**
69
* Returns the MappingProvider used by this configuration
70
* @return MappingProvider instance
71
*/
72
public MappingProvider mappingProvider();
73
74
/**
75
* Creates new configuration with different MappingProvider
76
* @param newMappingProvider MappingProvider to use
77
* @return New configuration instance
78
*/
79
public Configuration mappingProvider(MappingProvider newMappingProvider);
80
81
/**
82
* Returns the options used by this configuration
83
* @return Immutable set of options
84
*/
85
public Set<Option> getOptions();
86
87
/**
88
* Creates new configuration by adding options to existing ones
89
* @param options Options to add
90
* @return New configuration instance
91
*/
92
public Configuration addOptions(Option... options);
93
94
/**
95
* Creates new configuration with specified options (replaces existing)
96
* @param options Options to set
97
* @return New configuration instance
98
*/
99
public Configuration setOptions(Option... options);
100
101
/**
102
* Checks if configuration contains a specific option
103
* @param option Option to check
104
* @return true if option is present
105
*/
106
public boolean containsOption(Option option);
107
```
108
109
**Usage Examples:**
110
111
```java
112
import com.jayway.jsonpath.Configuration;
113
import com.jayway.jsonpath.Option;
114
import com.jayway.jsonpath.spi.json.GsonJsonProvider;
115
import com.jayway.jsonpath.spi.mapper.GsonMappingProvider;
116
117
Configuration config = Configuration.defaultConfiguration();
118
119
// Check current providers
120
JsonProvider currentJsonProvider = config.jsonProvider();
121
MappingProvider currentMappingProvider = config.mappingProvider();
122
123
// Create configuration with different providers
124
Configuration gsonConfig = config
125
.jsonProvider(new GsonJsonProvider())
126
.mappingProvider(new GsonMappingProvider());
127
128
// Work with options
129
Set<Option> currentOptions = config.getOptions();
130
boolean suppressesExceptions = config.containsOption(Option.SUPPRESS_EXCEPTIONS);
131
132
// Add options
133
Configuration withSuppression = config.addOptions(Option.SUPPRESS_EXCEPTIONS);
134
135
// Replace options
136
Configuration onlyReturnLists = config.setOptions(Option.ALWAYS_RETURN_LIST);
137
```
138
139
### Evaluation Listeners
140
141
Methods for managing evaluation listeners that monitor path evaluation progress.
142
143
```java { .api }
144
/**
145
* Creates new configuration by adding evaluation listeners
146
* @param evaluationListener Listeners to add
147
* @return New configuration with added listeners
148
*/
149
public Configuration addEvaluationListeners(EvaluationListener... evaluationListener);
150
151
/**
152
* Creates new configuration with specified evaluation listeners (replaces existing)
153
* @param evaluationListener Listeners to set
154
* @return New configuration with specified listeners
155
*/
156
public Configuration setEvaluationListeners(EvaluationListener... evaluationListener);
157
158
/**
159
* Returns the evaluation listeners used by this configuration
160
* @return Collection of evaluation listeners
161
*/
162
public Collection<EvaluationListener> getEvaluationListeners();
163
```
164
165
**Usage Examples:**
166
167
```java
168
import com.jayway.jsonpath.Configuration;
169
import com.jayway.jsonpath.EvaluationListener;
170
import java.util.Collection;
171
172
// Create evaluation listener
173
EvaluationListener listener = new EvaluationListener() {
174
@Override
175
public EvaluationContinuation resultFound(FoundResult found) {
176
System.out.println("Result found: " + found.result());
177
return EvaluationContinuation.CONTINUE;
178
}
179
};
180
181
// Add listener to configuration
182
Configuration config = Configuration.defaultConfiguration()
183
.addEvaluationListeners(listener);
184
185
// Check listeners
186
Collection<EvaluationListener> listeners = config.getEvaluationListeners();
187
188
// Replace all listeners
189
EvaluationListener newListener = /* ... */;
190
Configuration configWithNewListener = config.setEvaluationListeners(newListener);
191
```
192
193
### Configuration Builder
194
195
Builder class for constructing Configuration instances with fluent API.
196
197
```java { .api }
198
/**
199
* Builder class for creating Configuration instances
200
*/
201
public static class ConfigurationBuilder {
202
/**
203
* Sets the JsonProvider for the configuration
204
* @param provider JsonProvider to use
205
* @return Builder instance for chaining
206
*/
207
public ConfigurationBuilder jsonProvider(JsonProvider provider);
208
209
/**
210
* Sets the MappingProvider for the configuration
211
* @param provider MappingProvider to use
212
* @return Builder instance for chaining
213
*/
214
public ConfigurationBuilder mappingProvider(MappingProvider provider);
215
216
/**
217
* Sets options for the configuration
218
* @param flags Option flags to set
219
* @return Builder instance for chaining
220
*/
221
public ConfigurationBuilder options(Option... flags);
222
223
/**
224
* Sets options from a set
225
* @param options Set of options to use
226
* @return Builder instance for chaining
227
*/
228
public ConfigurationBuilder options(Set<Option> options);
229
230
/**
231
* Sets evaluation listeners
232
* @param listener Array of evaluation listeners
233
* @return Builder instance for chaining
234
*/
235
public ConfigurationBuilder evaluationListener(EvaluationListener... listener);
236
237
/**
238
* Sets evaluation listeners from collection
239
* @param listeners Collection of evaluation listeners
240
* @return Builder instance for chaining
241
*/
242
public ConfigurationBuilder evaluationListener(Collection<EvaluationListener> listeners);
243
244
/**
245
* Builds the final Configuration instance
246
* @return Immutable Configuration instance
247
*/
248
public Configuration build();
249
}
250
```
251
252
**Usage Examples:**
253
254
```java
255
import com.jayway.jsonpath.Configuration;
256
import com.jayway.jsonpath.Option;
257
import com.jayway.jsonpath.spi.json.JacksonJsonProvider;
258
import com.jayway.jsonpath.spi.mapper.JsonSmartMappingProvider;
259
260
Configuration config = Configuration.builder()
261
.jsonProvider(new JacksonJsonProvider())
262
.mappingProvider(new JsonSmartMappingProvider())
263
.options(Option.SUPPRESS_EXCEPTIONS, Option.ALWAYS_RETURN_LIST)
264
.evaluationListener(debugListener)
265
.build();
266
```
267
268
### Configuration Options
269
270
Enumeration of available configuration options that control JsonPath behavior.
271
272
```java { .api }
273
/**
274
* Configuration options for controlling JsonPath evaluation behavior
275
*/
276
public enum Option {
277
/**
278
* Returns null for missing leaf values instead of omitting them
279
* Example: $.items[*].price returns [10.0, null, 5.0] instead of [10.0, 5.0]
280
*/
281
DEFAULT_PATH_LEAF_TO_NULL,
282
283
/**
284
* Forces all results to be returned as lists for consistency
285
* Definite paths return single-element lists instead of scalar values
286
*/
287
ALWAYS_RETURN_LIST,
288
289
/**
290
* Returns list of path strings instead of actual values
291
* Useful for understanding which paths matched the expression
292
*/
293
AS_PATH_LIST,
294
295
/**
296
* Suppresses exceptions during path evaluation
297
* Returns null or empty list instead of throwing exceptions
298
*/
299
SUPPRESS_EXCEPTIONS,
300
301
/**
302
* Requires all properties in indefinite paths to exist
303
* Throws PathNotFoundException if any property is missing
304
*/
305
REQUIRE_PROPERTIES
306
}
307
```
308
309
**Usage Examples:**
310
311
```java
312
import com.jayway.jsonpath.JsonPath;
313
import com.jayway.jsonpath.Configuration;
314
import com.jayway.jsonpath.Option;
315
import java.util.List;
316
317
String json = "{ \"items\": [{ \"name\": \"A\", \"price\": 10 }, { \"name\": \"B\" }] }";
318
319
// DEFAULT_PATH_LEAF_TO_NULL
320
Configuration config1 = Configuration.builder()
321
.options(Option.DEFAULT_PATH_LEAF_TO_NULL)
322
.build();
323
List<Object> prices1 = JsonPath.using(config1).parse(json).read("$.items[*].price");
324
// Result: [10, null] instead of [10]
325
326
// ALWAYS_RETURN_LIST
327
Configuration config2 = Configuration.builder()
328
.options(Option.ALWAYS_RETURN_LIST)
329
.build();
330
List<String> name = JsonPath.using(config2).parse(json).read("$.items[0].name");
331
// Result: ["A"] instead of "A"
332
333
// AS_PATH_LIST
334
Configuration config3 = Configuration.builder()
335
.options(Option.AS_PATH_LIST)
336
.build();
337
List<String> paths = JsonPath.using(config3).parse(json).read("$.items[*].name");
338
// Result: ["$['items'][0]['name']", "$['items'][1]['name']"]
339
340
// SUPPRESS_EXCEPTIONS
341
Configuration config4 = Configuration.builder()
342
.options(Option.SUPPRESS_EXCEPTIONS)
343
.build();
344
Object result = JsonPath.using(config4).parse(json).read("$.nonexistent.path");
345
// Result: null instead of PathNotFoundException
346
```
347
348
### Defaults Interface
349
350
Interface for defining default configuration values.
351
352
```java { .api }
353
/**
354
* Interface for providing default configuration values
355
*/
356
public interface Defaults {
357
/**
358
* Returns the default JsonProvider
359
* @return Default JsonProvider instance
360
*/
361
JsonProvider jsonProvider();
362
363
/**
364
* Returns default options
365
* @return Set of default options
366
*/
367
Set<Option> options();
368
369
/**
370
* Returns the default MappingProvider
371
* @return Default MappingProvider instance
372
*/
373
MappingProvider mappingProvider();
374
}
375
```
376
377
**Usage Examples:**
378
379
```java
380
import com.jayway.jsonpath.Configuration;
381
import com.jayway.jsonpath.Option;
382
import com.jayway.jsonpath.spi.json.JsonProvider;
383
import com.jayway.jsonpath.spi.mapper.MappingProvider;
384
import java.util.Set;
385
import java.util.EnumSet;
386
387
// Custom defaults implementation
388
Configuration.Defaults customDefaults = new Configuration.Defaults() {
389
public JsonProvider jsonProvider() {
390
return new CustomJsonProvider();
391
}
392
393
public Set<Option> options() {
394
return EnumSet.of(Option.SUPPRESS_EXCEPTIONS, Option.ALWAYS_RETURN_LIST);
395
}
396
397
public MappingProvider mappingProvider() {
398
return new CustomMappingProvider();
399
}
400
};
401
402
// Set as global defaults
403
Configuration.setDefaults(customDefaults);
404
405
// Now all default configurations will use these settings
406
Configuration config = Configuration.defaultConfiguration();
407
```
408
409
### Cache SPI
410
411
JsonPath provides a pluggable cache system for compiled path expressions to improve performance when the same paths are used repeatedly.
412
413
```java { .api }
414
/**
415
* Interface for caching compiled JsonPath instances
416
*/
417
public interface Cache {
418
/**
419
* Retrieves a compiled JsonPath from the cache
420
* @param key Path string used as cache key
421
* @return Cached JsonPath instance, or null if not found
422
*/
423
JsonPath get(String key);
424
425
/**
426
* Stores a compiled JsonPath in the cache
427
* @param key Path string to use as cache key
428
* @param jsonPath Compiled JsonPath to cache
429
*/
430
void put(String key, JsonPath jsonPath);
431
}
432
433
/**
434
* Provider for managing JsonPath cache instances
435
*/
436
public class CacheProvider {
437
/**
438
* Sets the cache implementation to use globally
439
* @param cache Cache implementation
440
* @throws JsonPathException If cache is accessed before being set
441
*/
442
public static void setCache(Cache cache);
443
444
/**
445
* Returns the current cache implementation
446
* @return Cache instance in use
447
*/
448
public static Cache getCache();
449
}
450
```
451
452
**Built-in Cache Implementations:**
453
454
JsonPath ships with two cache implementations:
455
456
- `com.jayway.jsonpath.spi.cache.LRUCache` - Thread-safe LRU cache (default)
457
- `com.jayway.jsonpath.spi.cache.NOOPCache` - No-operation cache (disables caching)
458
459
**Usage Examples:**
460
461
```java
462
import com.jayway.jsonpath.spi.cache.Cache;
463
import com.jayway.jsonpath.spi.cache.CacheProvider;
464
import com.jayway.jsonpath.spi.cache.LRUCache;
465
import com.jayway.jsonpath.spi.cache.NOOPCache;
466
import com.jayway.jsonpath.JsonPath;
467
import java.util.concurrent.ConcurrentHashMap;
468
import java.util.Map;
469
470
// Use LRU cache with specific capacity
471
Cache lruCache = new LRUCache(100); // Cache up to 100 compiled paths
472
CacheProvider.setCache(lruCache);
473
474
// Disable caching entirely
475
Cache noopCache = new NOOPCache();
476
CacheProvider.setCache(noopCache);
477
478
// Custom cache implementation
479
Cache customCache = new Cache() {
480
private final Map<String, JsonPath> cache = new ConcurrentHashMap<>();
481
482
@Override
483
public JsonPath get(String key) {
484
return cache.get(key);
485
}
486
487
@Override
488
public void put(String key, JsonPath jsonPath) {
489
cache.put(key, jsonPath);
490
}
491
};
492
493
CacheProvider.setCache(customCache);
494
495
// Once cache is configured, compiled paths are automatically cached
496
JsonPath path1 = JsonPath.compile("$.store.book[*].author");
497
JsonPath path2 = JsonPath.compile("$.store.book[*].author"); // Retrieved from cache
498
499
// Check cache usage
500
Cache currentCache = CacheProvider.getCache();
501
JsonPath cachedPath = currentCache.get("$.store.book[*].author");
502
```
503
504
**Performance Considerations:**
505
506
- The cache must be configured before any JsonPath compilation occurs
507
- LRU cache is thread-safe and recommended for multi-threaded applications
508
- NOOP cache is useful for testing or when path expressions are not reused
509
- Custom cache implementations should be thread-safe for concurrent usage
510
511
**Advanced Configuration:**
512
513
```java
514
import com.jayway.jsonpath.Configuration;
515
import com.jayway.jsonpath.spi.cache.LRUCache;
516
import com.jayway.jsonpath.spi.cache.CacheProvider;
517
518
// Configure cache before creating configurations
519
CacheProvider.setCache(new LRUCache(200));
520
521
// Create configuration - will use the configured cache
522
Configuration config = Configuration.builder()
523
.options(Option.SUPPRESS_EXCEPTIONS)
524
.build();
525
526
// All JsonPath operations will benefit from caching
527
JsonPath path = JsonPath.compile("$.complex.nested[*].path");
528
```