Class JsonIo
This API uses a fluent builder pattern that splits JSON conversion into two parts:
- The initial conversion:
- For writing, you convert a Java object (or an intermediate
JsonObject
/Map
) to JSON (either as aString
or directly to anOutputStream
). - For reading, you start by parsing JSON from a source (
String
,InputStream
, or an in-memoryJsonObject
), and obtain a builder.
- For writing, you convert a Java object (or an intermediate
- The completion:
- Call either
asClass()
(for a concrete target class) orasType()
(to support generic types via aTypeHolder
) to complete the conversion.
- Call either
Note: JsonIo includes extensive type conversion capabilities for both primitive and complex types.
To view the complete list of supported conversions, examine the output of
main(String[])
or simply run the class directly from the command line.
Usage Examples:
-
1. Converting a Java object to JSON:
// Convert a Java object to a JSON String: String json = JsonIo.toJson(myObject, writeOptions); // Write a Java object as JSON to an OutputStream: JsonIo.toJson(outputStream, myObject, writeOptions);
-
2. Reading JSON into fully resolved Java objects:
// From a JSON String into a specific class: Person person = JsonIo.toJava(jsonString, readOptions).asClass(Person.class); // From an InputStream into a generic type (using TypeHolder): List<Person> people = JsonIo.toJava(inputStream, readOptions) .asType(new TypeHolder<List<Person>>(){});
-
3. Reading JSON into an intermediate representation (JsonObject/Map):
// Configure the ReadOptions to force returning JsonObjects (typically Maps) ReadOptions read = new ReadOptionsBuilder() .returnAsJsonObjects() .build(); // Parse the JSON into a Map (or nested Map structure) Map<String, Object> jsonMap = JsonIo.toJava(jsonString, read).asClass(Map.class);
In this case, simple Java types may be converted (or left as is forMap
types), andCollection
types will be converted appropriately.
Note:
- The builder returned by the initial JSON reading call must be completed with a call
to either
asClass()
orasType()
to perform the final conversion. - The nature of the resulting object—whether it is a fully resolved Java object or an intermediate
representation (typically a
Map
)—is determined by theReadOptionBuilder
settings (returnAsJavaObjects()
orreturnAsJsonObjects()
) passed to the call.
- Author:
- John DeRegnaucourt ([email protected])
Copyright (c) Cedar Software LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
License
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final class
Builder for converting a JsonObject (Map representation) to fully resolved Java objects.static final class
Builder for converting JSON from an InputStream to Java objects.static final class
Builder for converting a JSON string to Java objects. -
Method Summary
Modifier and TypeMethodDescriptionstatic <T> T
deepCopy
(Object source, ReadOptions readOptions, WriteOptions writeOptions) Creates a deep copy of an object by serializing it to JSON and then deserializing it back.static String
formatJson
(String json) Formats a JSON string with proper indentation and line breaks for readability.static void
Displays a list of all supported type conversions in JsonIo.static JsonIo.JavaObjectBuilder
toJava
(JsonObject jsonObject, ReadOptions readOptions) Begins the process of converting a JsonObject (Map representation) to fully resolved Java objects.static JsonIo.JavaStreamBuilder
toJava
(InputStream in, ReadOptions readOptions) Begins the process of converting JSON from an InputStream to Java objects.static JsonIo.JavaStringBuilder
toJava
(String json, ReadOptions readOptions) Begins the process of converting a JSON string to Java objects.static void
toJson
(OutputStream out, Object source, WriteOptions writeOptions) Writes a Java object as JSON directly to an OutputStream.static String
toJson
(Object srcObject, WriteOptions writeOptions) Converts a Java object to a JSON string representation.static <T> T
toObjects
(JsonObject jsonObject, ReadOptions readOptions, Class<T> rootType) Converts a JsonObject (Map representation) to a Java object of the specified class.static <T> T
toObjects
(InputStream in, ReadOptions readOptions, Class<T> rootType) Converts JSON from an InputStream to a Java object of the specified class.static <T> T
toObjects
(String json, ReadOptions readOptions, Class<T> rootType) Converts a JSON string to a Java object of the specified class.
-
Method Details
-
toJson
Converts a Java object to a JSON string representation.This method serializes the provided source object into a JSON string according to the specified write options. The source object can be any Java object, including primitives, collections, arrays, custom classes, or even an intermediate JsonObject (Map) representation that was obtained from a previous read operation.
Examples:
// Basic usage with default options String json = JsonIo.toJson(myObject, null); // With custom write options WriteOptions options = new WriteOptionsBuilder() .prettyPrint(true) .showTypeInfoMinimal() .build(); String json = JsonIo.toJson(myObject, options); // Converting a Map/JsonObject to JSON Map<String, Object> map = JsonIo.toJava(jsonString, readOptions).asClass(Map.class); // ... modify the map ... String updatedJson = JsonIo.toJson(map, writeOptions);
- Parameters:
srcObject
- the Java object to convert to JSON; can be any object including primitives, collections, custom classes, or a JsonObject/MapwriteOptions
- configuration options for controlling the JSON output format; if null, default options will be used- Returns:
- a JSON string representation of the source object
- Throws:
JsonIoException
- if an error occurs during the serialization process
-
toJson
Writes a Java object as JSON directly to an OutputStream.This method serializes the provided source object into JSON and writes the result to the specified output stream. This is useful for scenarios where you want to stream JSON output directly to a file, network connection, or other destination without creating an intermediate string representation.
By default, the output stream is closed after writing. To keep it open (e.g., when writing multiple objects), configure the write options with
writeOptions.closeStream(false)
.Examples:
// Write JSON to a file try (FileOutputStream fos = new FileOutputStream("data.json")) { JsonIo.toJson(fos, myObject, writeOptions); } // Stream multiple objects without closing between writes WriteOptions options = new WriteOptionsBuilder() .closeStream(false) .build(); for (MyObject obj : objects) { JsonIo.toJson(outputStream, obj, options); // The stream remains open for the next object } outputStream.close(); // Close manually when done
- Parameters:
out
- the output stream where the JSON will be written; must not be nullsource
- the Java object to convert to JSONwriteOptions
- configuration options controlling the JSON output format; if null, default options will be used- Throws:
JsonIoException
- if an error occurs during serializationIllegalArgumentException
- if the output stream is null
-
toJava
Begins the process of converting a JSON string to Java objects.This method is the first step in a two-step JSON parsing process. It takes a JSON string and parsing options, and returns a builder that can complete the conversion to the desired Java type. The returned builder provides two completion methods:
asClass(Class)
- For converting to a specific classasType(TypeHolder)
- For converting to a generic type likeList<Person>
Examples:
// Parse JSON to a specific class Person person = JsonIo.toJava(jsonString, options).asClass(Person.class); // Parse to a generic collection type List<Person> people = JsonIo.toJava(jsonString, options) .asType(new TypeHolder<List<Person>>(){}); // Parse to an intermediate Map representation ReadOptions mapOptions = new ReadOptionsBuilder() .returnAsJsonObjects() .build(); Map<String, Object> dataMap = JsonIo.toJava(jsonString, mapOptions).asClass(Map.class);
The behavior of this method is controlled by the
ReadOptions
. In particular:- With
ReadOptions.returnAsJavaObjects()
(default), the result will be fully instantiated Java objects of the specified type. - With
ReadOptions.returnAsJsonObjects()
, the result will be the intermediate Map representation (JsonObjects) that can later be manipulated or converted.
- Parameters:
json
- the JSON string to parse; if null, an empty string will be usedreadOptions
- configuration options for controlling how the JSON is parsed; if null, default options will be used- Returns:
- a builder to complete the conversion by specifying the target type
-
toJava
Begins the process of converting JSON from an InputStream to Java objects.This method is the first step in a two-step JSON parsing process. It takes a JSON input stream and parsing options, and returns a builder that can complete the conversion to the desired Java type. The returned builder provides two completion methods:
asClass(Class)
- For converting to a specific classasType(TypeHolder)
- For converting to a generic type likeList<Person>
By default, the input stream is closed after reading. To keep it open (e.g., when reading multiple JSON objects), configure the read options with
readOptions.closeStream(false)
.Examples:
// Parse JSON from a file try (FileInputStream fis = new FileInputStream("data.json")) { Person person = JsonIo.toJava(fis, options).asClass(Person.class); } // Parse JSON from a stream to a generic type List<Person> people = JsonIo.toJava(inputStream, options) .asType(new TypeHolder<List<Person>>(){});
- Parameters:
in
- the input stream containing JSON; must not be nullreadOptions
- configuration options for controlling how the JSON is parsed; if null, default options will be used- Returns:
- a builder to complete the conversion by specifying the target type
- Throws:
IllegalArgumentException
- if the input stream is null
-
toJava
Begins the process of converting a JsonObject (Map representation) to fully resolved Java objects.This method is part of the two-phase parsing capability of JsonIo. It takes a JsonObject (typically a Map structure that was returned from a previous call with
ReadOptions.returnAsJsonObjects()
) and converts it to a specific Java type. This allows you to examine and modify the parsed JSON structure before finalizing the conversion to Java objects.The returned builder provides two completion methods:
asClass(Class)
- For converting to a specific classasType(TypeHolder)
- For converting to a generic type likeList<Person>
Examples:
// First parse JSON to a Map representation ReadOptions mapOptions = new ReadOptionsBuilder() .returnAsJsonObjects() .build(); Map<String, Object> jsonMap = JsonIo.toJava(jsonString, mapOptions).asClass(Map.class); // Modify the map structure if needed jsonMap.put("extraProperty", "new value"); // Then convert the modified structure to Java objects Person person = JsonIo.toJava(jsonMap, readOptions).asClass(Person.class);
- Parameters:
jsonObject
- the JsonObject (typically a Map) to convert; must not be nullreadOptions
- configuration options for controlling the conversion; if null, default options will be used- Returns:
- a builder to complete the conversion by specifying the target type
- Throws:
IllegalArgumentException
- if the jsonObject is null
-
formatJson
Formats a JSON string with proper indentation and line breaks for readability.This method takes a potentially minified or poorly formatted JSON string and converts it to a well-formatted, human-readable version with proper indentation and line breaks. This is useful for debugging, logging, or displaying JSON in a user interface.
Note that the formatting is purely cosmetic and does not change the semantic meaning of the JSON content.
Example:
String minifiedJson = "{\"name\":\"John\",\"age\":30,\"address\":{\"city\":\"New York\",\"zip\":\"10001\"}}"; String prettyJson = JsonIo.formatJson(minifiedJson); System.out.println(prettyJson); // Output: // { // "name": "John", // "age": 30, // "address": { // "city": "New York", // "zip": "10001" // } // }
- Parameters:
json
- the JSON string to format; if invalid JSON is provided, the method may throw an exception- Returns:
- a formatted, indented JSON string for improved readability
-
deepCopy
Creates a deep copy of an object by serializing it to JSON and then deserializing it back.This method provides a convenient way to create a completely detached copy of an object graph. It works by converting the object to JSON and then back to a new instance, effectively "cloning" the entire object structure including all nested objects.
This approach can be particularly useful when you need to:
- Create a true deep copy of a complex object graph
- Detach an object from its original references
- Create a snapshot of an object's state
Example:
// Create a deep copy of an object Person original = new Person("John", 30); Person copy = JsonIo.deepCopy(original, null, null); // Verify the copy is independent original.setName("Jane"); System.out.println(copy.getName()); // Still "John"
The method sets special write options to ensure proper copying, but you can provide custom read and write options to further control the process if needed.
- Type Parameters:
T
- the type of the object being copied- Parameters:
source
- the object to copy; if null, null will be returnedreadOptions
- options for controlling deserialization; if null, default options will be usedwriteOptions
- options for controlling serialization; if null, default options will be used- Returns:
- a deep copy of the original object, or null if the source was null
-
toObjects
Converts a JSON string to a Java object of the specified class.Note: This method will be deprecated in a future release. Please use the
toJava(String, ReadOptions)
method withasClass()
orasType()
instead.This method parses the provided JSON string and converts it to an instance of the specified class.
Example:
// Legacy approach: Person person = JsonIo.toObjects(jsonString, readOptions, Person.class); // Recommended new approach: Person person = JsonIo.toJava(jsonString, readOptions).asClass(Person.class);
- Type Parameters:
T
- the type of the resulting Java object- Parameters:
json
- the JSON string to parsereadOptions
- options for controlling the parsing; if null, default options will be usedrootType
- the class to convert the JSON to- Returns:
- an instance of the specified class populated from the JSON
-
toObjects
Converts JSON from an InputStream to a Java object of the specified class.Note: This method will be deprecated in a future release. Please use the
toJava(InputStream, ReadOptions)
method withasClass()
orasType()
instead.This method reads JSON from the provided input stream and converts it to an instance of the specified class.
Example:
// Legacy approach: Person person = JsonIo.toObjects(inputStream, readOptions, Person.class); // Recommended new approach: Person person = JsonIo.toJava(inputStream, readOptions).asClass(Person.class);
- Type Parameters:
T
- the type of the resulting Java object- Parameters:
in
- the input stream containing JSONreadOptions
- options for controlling the parsing; if null, default options will be usedrootType
- the class to convert the JSON to- Returns:
- an instance of the specified class populated from the JSON
-
toObjects
Converts a JsonObject (Map representation) to a Java object of the specified class.Note: This method will be deprecated in a future release. Please use the
toJava(JsonObject, ReadOptions)
method withasClass()
orasType()
instead.This method converts the provided JsonObject to an instance of the specified class.
Example:
// Legacy approach: Person person = JsonIo.toObjects(jsonObject, readOptions, Person.class); // Recommended new approach: Person person = JsonIo.toJava(jsonObject, readOptions).asClass(Person.class);
- Type Parameters:
T
- the type of the resulting Java object- Parameters:
jsonObject
- the JsonObject to convertreadOptions
- options for controlling the conversion; if null, default options will be usedrootType
- the class to convert the JsonObject to- Returns:
- an instance of the specified class populated from the JsonObject
-
main
Displays a list of all supported type conversions in JsonIo.When executed directly, this method prints out a comprehensive JSON representation of all the type conversions supported by the underlying
Converter
used by JsonIo. This includes conversions between primitive types, temporal types, collections, and more specialized Java types.The extensive conversion capabilities are powered by the java-util library's
Converter
framework, which provides a robust system for transforming between nearly any Java types.Pro Tip: Run this method to see the full range of automatic type conversions available in JsonIo. This can be helpful when working with heterogeneous data or when you need to convert between different Java types during deserialization.
java -cp your-classpath com.cedarsoftware.io.JsonIo
- Parameters:
args
- command line arguments (not used)
-