0
# Serialization Utilities
1
2
Comprehensive serialization system supporting JSON and XML with pluggable serializers, binary data handling, and integration with popular Java serialization libraries like Jackson and GSON.
3
4
## Capabilities
5
6
### BinaryData
7
8
Flexible binary data representation supporting multiple content sources with lazy serialization and efficient memory usage.
9
10
```java { .api }
11
/**
12
* BinaryData is a convenient data interchange class for use throughout the Azure SDK for Java.
13
*/
14
class BinaryData {
15
/**
16
* Creates an instance of BinaryData from the given InputStream.
17
* @param inputStream InputStream that BinaryData will represent
18
* @return BinaryData representing the InputStream
19
*/
20
public static BinaryData fromStream(InputStream inputStream);
21
22
/**
23
* Creates an instance of BinaryData from the given InputStream.
24
* @param inputStream InputStream that BinaryData will represent
25
* @param length The length of the InputStream in bytes
26
* @return BinaryData representing the InputStream
27
*/
28
public static BinaryData fromStream(InputStream inputStream, Long length);
29
30
/**
31
* Creates an instance of BinaryData from the given Flux of ByteBuffer.
32
* @param data Flux of ByteBuffer that BinaryData will represent
33
* @return BinaryData representing the Flux of ByteBuffer
34
*/
35
public static BinaryData fromFlux(Flux<ByteBuffer> data);
36
37
/**
38
* Creates an instance of BinaryData from the given Flux of ByteBuffer.
39
* @param data Flux of ByteBuffer that BinaryData will represent
40
* @param length The length of the data in bytes
41
* @param bufferAggregation Whether to aggregate the Flux into a single buffer
42
* @return BinaryData representing the Flux of ByteBuffer
43
*/
44
public static BinaryData fromFlux(Flux<ByteBuffer> data, Long length, boolean bufferAggregation);
45
46
/**
47
* Creates an instance of BinaryData from the given byte array.
48
* @param data byte array that BinaryData will represent
49
* @return BinaryData representing the byte array
50
*/
51
public static BinaryData fromBytes(byte[] data);
52
53
/**
54
* Creates an instance of BinaryData from the given String.
55
* @param data String that BinaryData will represent
56
* @return BinaryData representing the String
57
*/
58
public static BinaryData fromString(String data);
59
60
/**
61
* Creates an instance of BinaryData by serializing the given Object using default JsonSerializer.
62
* @param data Object that BinaryData will represent
63
* @return BinaryData representing the serialized Object
64
*/
65
public static BinaryData fromObject(Object data);
66
67
/**
68
* Creates an instance of BinaryData by serializing the given Object using provided JsonSerializer.
69
* @param data Object that BinaryData will represent
70
* @param serializer JsonSerializer to use for serialization
71
* @return BinaryData representing the serialized Object
72
*/
73
public static BinaryData fromObject(Object data, ObjectSerializer serializer);
74
75
/**
76
* Creates an instance of BinaryData from the given file.
77
* @param file Path to the file that BinaryData will represent
78
* @return BinaryData representing the file content
79
*/
80
public static BinaryData fromFile(Path file);
81
82
/**
83
* Creates an instance of BinaryData from the given file.
84
* @param file Path to the file that BinaryData will represent
85
* @param chunkSize Size of each chunk to read from the file
86
* @return BinaryData representing the file content
87
*/
88
public static BinaryData fromFile(Path file, int chunkSize);
89
90
/**
91
* Returns the content of this BinaryData instance as a byte array.
92
* @return byte array representation of this BinaryData
93
*/
94
public byte[] toBytes();
95
96
/**
97
* Returns the content of this BinaryData as a String.
98
* @return String representation of this BinaryData
99
*/
100
@Override
101
public String toString();
102
103
/**
104
* Returns the content of this BinaryData as a String using the provided charset.
105
* @param charset Charset to use for decoding
106
* @return String representation using the specified charset
107
*/
108
public String toString(Charset charset);
109
110
/**
111
* Returns the content of this BinaryData as an Object of the given type.
112
* @param <T> Type of the Object
113
* @param clazz Class representing the Object's type
114
* @return Object representation of this BinaryData
115
*/
116
public <T> T toObject(Class<T> clazz);
117
118
/**
119
* Returns the content of this BinaryData as an Object of the given type.
120
* @param <T> Type of the Object
121
* @param typeReference TypeReference representing the Object's type
122
* @return Object representation of this BinaryData
123
*/
124
public <T> T toObject(TypeReference<T> typeReference);
125
126
/**
127
* Returns the content of this BinaryData as an Object of the given type using the provided ObjectSerializer.
128
* @param <T> Type of the Object
129
* @param clazz Class representing the Object's type
130
* @param serializer ObjectSerializer to use for deserialization
131
* @return Object representation of this BinaryData
132
*/
133
public <T> T toObject(Class<T> clazz, ObjectSerializer serializer);
134
135
/**
136
* Returns the content of this BinaryData as an Object of the given type using the provided ObjectSerializer.
137
* @param <T> Type of the Object
138
* @param typeReference TypeReference representing the Object's type
139
* @param serializer ObjectSerializer to use for deserialization
140
* @return Object representation of this BinaryData
141
*/
142
public <T> T toObject(TypeReference<T> typeReference, ObjectSerializer serializer);
143
144
/**
145
* Returns the content of this BinaryData as an InputStream.
146
* @return InputStream representation of this BinaryData
147
*/
148
public InputStream toStream();
149
150
/**
151
* Returns the content of this BinaryData as a Flux of ByteBuffer.
152
* @return Flux of ByteBuffer representation of this BinaryData
153
*/
154
public Flux<ByteBuffer> toFluxByteBuffer();
155
156
/**
157
* Returns the content of this BinaryData as a ReplayableStream.
158
* @return ReplayableStream representation of this BinaryData
159
*/
160
public ReplayableStream toReplayableStream();
161
162
/**
163
* Writes the contents of this BinaryData to the given OutputStream.
164
* @param outputStream OutputStream to write to
165
*/
166
public void writeTo(OutputStream outputStream);
167
168
/**
169
* Writes the contents of this BinaryData to the given WritableByteChannel.
170
* @param channel WritableByteChannel to write to
171
* @return Number of bytes written
172
*/
173
public long writeTo(WritableByteChannel channel);
174
175
/**
176
* Returns the length of the content.
177
* @return Length of the content, or null if unknown
178
*/
179
public Long getLength();
180
181
/**
182
* Checks if the content can be replayed.
183
* @return true if content can be replayed, false otherwise
184
*/
185
public boolean isReplayable();
186
}
187
```
188
189
### JsonSerializer Interface
190
191
Core interface for JSON serialization with support for streams, bytes, and type-safe operations.
192
193
```java { .api }
194
/**
195
* Generic interface covering basic JSON serialization and deserialization methods.
196
*/
197
interface JsonSerializer {
198
/**
199
* Reads a JSON stream into its object representation.
200
* @param <T> Type of the object
201
* @param stream JSON stream
202
* @param type Type to deserialize into
203
* @return Object representation of the JSON
204
*/
205
<T> T deserialize(InputStream stream, Type type);
206
207
/**
208
* Reads a JSON byte array into its object representation.
209
* @param <T> Type of the object
210
* @param bytes JSON byte array
211
* @param type Type to deserialize into
212
* @return Object representation of the JSON
213
*/
214
<T> T deserialize(byte[] bytes, Type type);
215
216
/**
217
* Reads a JSON string into its object representation.
218
* @param <T> Type of the object
219
* @param json JSON string
220
* @param type Type to deserialize into
221
* @return Object representation of the JSON
222
*/
223
<T> T deserialize(String json, Type type);
224
225
/**
226
* Reads a JSON stream into its object representation.
227
* @param <T> Type of the object
228
* @param stream JSON stream
229
* @param type Type to deserialize into
230
* @return Mono containing object representation of the JSON
231
*/
232
<T> Mono<T> deserializeAsync(InputStream stream, Type type);
233
234
/**
235
* Converts the object into a JSON string.
236
* @param value Object to serialize
237
* @return JSON string representation
238
*/
239
String serialize(Object value);
240
241
/**
242
* Converts the object into a JSON byte array.
243
* @param value Object to serialize
244
* @return JSON byte array representation
245
*/
246
byte[] serializeToBytes(Object value);
247
248
/**
249
* Writes the object to the provided OutputStream as JSON.
250
* @param stream OutputStream to write to
251
* @param value Object to serialize
252
*/
253
void serialize(OutputStream stream, Object value);
254
255
/**
256
* Writes the object to the provided OutputStream as JSON asynchronously.
257
* @param stream OutputStream to write to
258
* @param value Object to serialize
259
* @return Mono representing the operation
260
*/
261
Mono<Void> serializeAsync(OutputStream stream, Object value);
262
}
263
```
264
265
### ObjectSerializer Interface
266
267
General object serialization interface supporting multiple encoding formats.
268
269
```java { .api }
270
/**
271
* Generic interface covering basic serialization and deserialization methods.
272
*/
273
interface ObjectSerializer {
274
/**
275
* Reads an object representation from a stream.
276
* @param <T> Type of the object
277
* @param stream Stream to read from
278
* @param type Type to deserialize into
279
* @return Object representation
280
*/
281
<T> T deserialize(InputStream stream, Type type);
282
283
/**
284
* Reads an object representation from a byte array.
285
* @param <T> Type of the object
286
* @param bytes Byte array to read from
287
* @param type Type to deserialize into
288
* @return Object representation
289
*/
290
<T> T deserialize(byte[] bytes, Type type);
291
292
/**
293
* Reads an object representation from a string.
294
* @param <T> Type of the object
295
* @param data String to read from
296
* @param type Type to deserialize into
297
* @return Object representation
298
*/
299
<T> T deserialize(String data, Type type);
300
301
/**
302
* Reads an object representation from a stream asynchronously.
303
* @param <T> Type of the object
304
* @param stream Stream to read from
305
* @param type Type to deserialize into
306
* @return Mono containing object representation
307
*/
308
<T> Mono<T> deserializeAsync(InputStream stream, Type type);
309
310
/**
311
* Writes an object to a stream.
312
* @param stream Stream to write to
313
* @param value Object to serialize
314
*/
315
void serialize(OutputStream stream, Object value);
316
317
/**
318
* Converts an object to a string.
319
* @param value Object to serialize
320
* @return String representation
321
*/
322
String serialize(Object value);
323
324
/**
325
* Converts an object to a byte array.
326
* @param value Object to serialize
327
* @return Byte array representation
328
*/
329
byte[] serializeToBytes(Object value);
330
331
/**
332
* Writes an object to a stream asynchronously.
333
* @param stream Stream to write to
334
* @param value Object to serialize
335
* @return Mono representing the operation
336
*/
337
Mono<Void> serializeAsync(OutputStream stream, Object value);
338
}
339
```
340
341
### SerializerAdapter Interface
342
343
Adapter interface providing serialization operations with encoding support.
344
345
```java { .api }
346
/**
347
* An interface defining the behaviors of a serializer.
348
*/
349
interface SerializerAdapter {
350
/**
351
* Serializes an object into a string.
352
* @param object The object to serialize
353
* @param encoding The encoding to use for serialization
354
* @return The serialized string
355
*/
356
String serialize(Object object, SerializerEncoding encoding);
357
358
/**
359
* Serializes an object into a raw string without encoding information.
360
* @param object The object to serialize
361
* @return The serialized string
362
*/
363
String serializeRaw(Object object);
364
365
/**
366
* Serializes an object into a list of objects.
367
* @param object The object to serialize
368
* @param encoding The encoding to use for serialization
369
* @return The serialized list
370
*/
371
String serializeList(Object object, CollectionFormat format);
372
373
/**
374
* Deserializes a string into a specified type.
375
* @param <U> The type to deserialize into
376
* @param value The string to deserialize
377
* @param type The type to deserialize into
378
* @param encoding The encoding used for deserialization
379
* @return The deserialized object
380
*/
381
<U> U deserialize(String value, Type type, SerializerEncoding encoding);
382
383
/**
384
* Deserializes an HttpResponse into a specified type.
385
* @param <U> The type to deserialize into
386
* @param httpResponse The HTTP response to deserialize
387
* @param type The type to deserialize into
388
* @return The deserialized object
389
*/
390
<U> U deserialize(HttpResponse httpResponse, Type type);
391
392
/**
393
* Deserializes an HttpResponse into a specified type with additional headers.
394
* @param <U> The type to deserialize into
395
* @param httpResponse The HTTP response to deserialize
396
* @param type The type to deserialize into
397
* @param headerType The type for response headers
398
* @return The deserialized object with headers
399
*/
400
<U> U deserialize(HttpResponse httpResponse, Type type, Type headerType);
401
}
402
```
403
404
### SerializerEncoding Enum
405
406
Enumeration of supported serialization encoding formats.
407
408
```java { .api }
409
/**
410
* Supported serialization encoding formats.
411
*/
412
enum SerializerEncoding {
413
/**
414
* JavaScript Object Notation (JSON) format.
415
*/
416
JSON,
417
418
/**
419
* eXtensible Markup Language (XML) format.
420
*/
421
XML;
422
423
/**
424
* Creates a SerializerEncoding from a string value.
425
* @param value String representation
426
* @return Corresponding SerializerEncoding
427
*/
428
public static SerializerEncoding fromString(String value);
429
}
430
```
431
432
### JsonSerializerProvider Interface
433
434
Service provider interface for creating JsonSerializer instances.
435
436
```java { .api }
437
/**
438
* Service Provider Interface (SPI) for JsonSerializer.
439
*/
440
interface JsonSerializerProvider {
441
/**
442
* Creates a JsonSerializer instance.
443
* @return JsonSerializer instance
444
*/
445
JsonSerializer createInstance();
446
}
447
```
448
449
### TypeReference
450
451
Type reference class for handling generic types during deserialization.
452
453
```java { .api }
454
/**
455
* This class represents a reference to a generic type.
456
*/
457
abstract class TypeReference<T> {
458
/**
459
* Protected constructor for TypeReference.
460
*/
461
protected TypeReference();
462
463
/**
464
* Gets the generic type represented by this TypeReference.
465
* @return Type represented by this reference
466
*/
467
public Type getJavaType();
468
}
469
```
470
471
### ReplayableStream
472
473
Stream that can be replayed multiple times for efficient data handling.
474
475
```java { .api }
476
/**
477
* A stream that can be replayed (reset and read again).
478
*/
479
interface ReplayableStream {
480
/**
481
* Gets the content of this ReplayableStream as an InputStream.
482
* @return InputStream representing the stream content
483
*/
484
InputStream toStream();
485
486
/**
487
* Gets the content of this ReplayableStream as a Flux of ByteBuffer.
488
* @return Flux of ByteBuffer representing the stream content
489
*/
490
Flux<ByteBuffer> toFluxByteBuffer();
491
492
/**
493
* Gets the length of the content in bytes.
494
* @return Length in bytes, or null if unknown
495
*/
496
Long getLength();
497
498
/**
499
* Resets the stream to the beginning.
500
*/
501
void reset();
502
503
/**
504
* Marks the current position in the stream.
505
* @param readLimit Maximum bytes that can be read before mark becomes invalid
506
*/
507
void mark(int readLimit);
508
509
/**
510
* Checks if this stream supports mark and reset operations.
511
* @return true if mark/reset is supported
512
*/
513
boolean markSupported();
514
}
515
```
516
517
## Usage Examples
518
519
### Working with BinaryData
520
521
```java
522
import com.azure.core.util.BinaryData;
523
import com.azure.core.util.serializer.TypeReference;
524
import java.io.InputStream;
525
import java.util.List;
526
import java.util.Map;
527
528
// Create BinaryData from different sources
529
BinaryData fromString = BinaryData.fromString("{\"name\":\"John\",\"age\":30}");
530
BinaryData fromBytes = BinaryData.fromBytes("Hello World".getBytes());
531
532
// Create from file
533
Path filePath = Paths.get("data.json");
534
BinaryData fromFile = BinaryData.fromFile(filePath);
535
536
// Create from InputStream
537
InputStream inputStream = // ... get input stream
538
BinaryData fromStream = BinaryData.fromStream(inputStream);
539
540
// Serialize objects to BinaryData
541
User user = new User("Alice", "alice@example.com");
542
BinaryData fromObject = BinaryData.fromObject(user);
543
544
// Convert BinaryData to different formats
545
String jsonString = fromObject.toString();
546
byte[] jsonBytes = fromObject.toBytes();
547
InputStream stream = fromObject.toStream();
548
549
// Deserialize to objects
550
User deserializedUser = fromObject.toObject(User.class);
551
552
// Handle generic types
553
List<String> stringList = List.of("item1", "item2", "item3");
554
BinaryData listData = BinaryData.fromObject(stringList);
555
List<String> deserializedList = listData.toObject(new TypeReference<List<String>>() {});
556
557
// Work with Maps
558
Map<String, Object> dataMap = Map.of("key1", "value1", "key2", 42);
559
BinaryData mapData = BinaryData.fromObject(dataMap);
560
Map<String, Object> deserializedMap = mapData.toObject(new TypeReference<Map<String, Object>>() {});
561
```
562
563
### Custom Serialization
564
565
```java
566
import com.azure.core.util.serializer.*;
567
568
// Using custom JsonSerializer
569
JsonSerializer customSerializer = // ... get custom serializer
570
User user = new User("Bob", "bob@example.com");
571
572
// Serialize with custom serializer
573
BinaryData customSerialized = BinaryData.fromObject(user, customSerializer);
574
575
// Deserialize with custom serializer
576
User deserializedUser = customSerialized.toObject(User.class, customSerializer);
577
578
// Working with different content types
579
BinaryData xmlData = BinaryData.fromString("<user><name>Charlie</name></user>");
580
// Note: XML deserialization would require appropriate ObjectSerializer
581
```
582
583
### Stream Operations
584
585
```java
586
import com.azure.core.util.BinaryData;
587
import reactor.core.publisher.Flux;
588
import java.nio.ByteBuffer;
589
590
// Create from Flux
591
Flux<ByteBuffer> dataFlux = // ... create flux of byte buffers
592
BinaryData fromFlux = BinaryData.fromFlux(dataFlux);
593
594
// Convert to Flux
595
Flux<ByteBuffer> backToFlux = fromFlux.toFluxByteBuffer();
596
597
// Write to OutputStream
598
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
599
fromFlux.writeTo(outputStream);
600
byte[] written = outputStream.toByteArray();
601
602
// Check properties
603
Long length = fromFlux.getLength();
604
boolean isReplayable = fromFlux.isReplayable();
605
606
System.out.println("Data length: " + length);
607
System.out.println("Is replayable: " + isReplayable);
608
```
609
610
### Working with TypeReference
611
612
```java
613
import com.azure.core.util.serializer.TypeReference;
614
import java.util.List;
615
import java.util.Map;
616
617
// Complex generic types
618
class ApiResponse<T> {
619
private T data;
620
private String status;
621
private Map<String, String> metadata;
622
623
// ... getters and setters
624
}
625
626
// Deserialize complex generic types
627
String jsonResponse = "{\"data\":[{\"id\":1,\"name\":\"Item1\"}],\"status\":\"success\"}";
628
BinaryData responseData = BinaryData.fromString(jsonResponse);
629
630
// Use TypeReference for complex generics
631
ApiResponse<List<Item>> response = responseData.toObject(
632
new TypeReference<ApiResponse<List<Item>>>() {}
633
);
634
635
// Work with nested generics
636
Map<String, List<User>> userGroups = responseData.toObject(
637
new TypeReference<Map<String, List<User>>>() {}
638
);
639
```
640
641
### Streaming Large Files
642
643
```java
644
import com.azure.core.util.BinaryData;
645
import java.nio.channels.WritableByteChannel;
646
import java.nio.file.Files;
647
import java.nio.file.StandardOpenOption;
648
649
// Handle large files efficiently
650
Path largeFile = Paths.get("large-file.dat");
651
BinaryData largeFileData = BinaryData.fromFile(largeFile, 8192); // 8KB chunks
652
653
// Stream to another location
654
Path destination = Paths.get("copied-file.dat");
655
try (WritableByteChannel channel = Files.newByteChannel(destination,
656
StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
657
long bytesWritten = largeFileData.writeTo(channel);
658
System.out.println("Copied " + bytesWritten + " bytes");
659
}
660
661
// Check if content can be replayed
662
if (largeFileData.isReplayable()) {
663
// Safe to read multiple times
664
byte[] firstRead = largeFileData.toBytes();
665
byte[] secondRead = largeFileData.toBytes(); // Will work for replayable content
666
}
667
```