Class JsonIo

java.lang.Object
com.cedarsoftware.io.JsonIo

public class JsonIo extends Object
JsonIo is the main entry point for converting between JSON and Java objects.

Two Modes for Reading JSON

JsonIo provides two distinct approaches for reading JSON, each optimized for different use cases:

1. Java Object Mode - toJava()

Deserializes JSON to fully-typed Java object graphs. Requires Java classes on classpath.


 // Parse to specific class
 Person person = JsonIo.toJava(jsonString, readOptions).asClass(Person.class);

 // Parse to generic type
 List<Person> people = JsonIo.toJava(jsonString, readOptions)
                             .asType(new TypeHolder<List<Person>>(){});
 

Use when: You have Java classes available and want type-safe, validated objects.

2. Map Mode - toMaps()

Deserializes JSON to Map<String, Object> graph. No Java classes required.


 // Parse JSON object to Map
 Map<String, Object> map = JsonIo.toMaps(jsonString).asClass(Map.class);

 // Parse JSON array to List
 List<Object> list = JsonIo.toMaps("[1,2,3]").asClass(List.class);

 // Parse any JSON type
 Object result = JsonIo.toMaps(jsonString).asClass(null);

 // Access preserved @type metadata (advanced)
 JsonObject obj = JsonIo.toMaps(jsonString).asClass(JsonObject.class);
 String typeString = obj.getTypeString();  // Original @type preserved
 

Use when: Parsing JSON without classes (HTTP middleware, log analysis, cross-JVM transport).

Writing JSON

Convert any Java object (or Map graph) to JSON:


 // To String
 String json = JsonIo.toJson(myObject, writeOptions);

 // To OutputStream
 JsonIo.toJson(outputStream, myObject, writeOptions);
 

Key Features

  • Type Safety: Java Object mode provides compile-time type checking
  • Class Independence: Map mode works without any classes on classpath
  • Metadata Preservation: @type strings preserved even when classes don't exist
  • Reference Handling: Circular references and object graphs handled automatically
  • Deterministic Output: Same JSON input always produces same Map structure (LinkedHashMap ordering)

Advanced Usage

Two-Phase Parsing: Parse to Map first, then convert to Java objects:


 // Phase 1: Parse to Map (inspect/modify)
 Map<String, Object> map = JsonIo.toMaps(jsonString).asClass(Map.class);
 map.put("newField", "added value");

 // Phase 2: Convert to Java object
 Person person = JsonIo.toJava((JsonObject) map, readOptions).asClass(Person.class);
 

Note: JsonIo includes extensive type conversion capabilities. To view all supported conversions, run main(String[]) from the command line.

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.
  • Method Details

    • toJson

      public static String toJson(Object srcObject, WriteOptions writeOptions)
      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/Map
      writeOptions - 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

      public static void toJson(OutputStream out, Object source, WriteOptions writeOptions)
      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 null
      source - the Java object to convert to JSON
      writeOptions - configuration options controlling the JSON output format; if null, default options will be used
      Throws:
      JsonIoException - if an error occurs during serialization
      IllegalArgumentException - if the output stream is null
    • toMaps

      public static JsonIo.JavaStringBuilder toMaps(String json)
      Parses JSON into a Map<String, Object> graph without requiring Java classes on classpath.

      This method provides a class-independent way to parse any JSON structure. The returned Map uses deterministic ordering (LinkedHashMap) and preserves JSON structure including:

      • Objects → Map<String, Object>
      • Arrays → Object[]
      • Primitives → Long, Double, Boolean, String

      Implementation Note: The actual return type is JsonObject (which extends LinkedHashMap). This means you can safely cast to JsonObject to access preserved metadata:

      
       // Access as Map
       Map<String, Object> map = JsonIo.toMaps(jsonString);
       String name = (String) map.get("name");
      
       // Access metadata (advanced usage)
       JsonObject obj = (JsonObject) JsonIo.toMaps(jsonString);
       String originalType = obj.getTypeString();  // Preserved @type value even if class doesn't exist
       

      Key Feature: This method automatically sets failOnUnknownType(false), allowing JSON with unknown @type entries to be parsed successfully. The original type strings are preserved in the JsonObject for later use.

      Use this when:

      • Parsing JSON on servers without domain classes (HTTP middleware)
      • Analyzing serialized object logs
      • Transporting data across JVMs with different classpaths
      • Inspecting/mutating JSON before converting to objects
      • Building generic JSON tools without class dependencies
      Parameters:
      json - the JSON string to parse; if null, an empty string will be used
      Returns:
      a builder to complete the conversion by specifying the target type
      Throws:
      JsonIoException - if an error occurs during parsing
      See Also:
    • toMaps

      public static JsonIo.JavaStringBuilder toMaps(String json, ReadOptions readOptions)
      Parses JSON into a Map graph with custom read options, returning a JsonValue builder.

      This method is identical to toMaps(String) but allows you to specify additional read options for controlling the parsing behavior (e.g., custom type aliases, missing field handlers).

      The method automatically configures returnAsJsonObjects() mode, which sets failOnUnknownType(false) by default. If you explicitly set failOnUnknownType(true) in your options, that will be honored.

      Example:

      
       ReadOptions options = new ReadOptionsBuilder()
           .aliasTypeName("com.example.OldClass", "com.example.NewClass")
           .build();
       Map<String, Object> map = JsonIo.toMaps(jsonString, options).asClass(Map.class);
       
      Parameters:
      json - the JSON string to parse; if null, an empty string will be used
      readOptions - configuration options; if null, defaults will be used
      Returns:
      a builder to complete the conversion by specifying the target type
      Throws:
      JsonIoException - if an error occurs during parsing
    • toMaps

      public static JsonIo.JavaStreamBuilder toMaps(InputStream in)
      Parses JSON from an InputStream into a Map graph without requiring Java classes.

      This is the streaming version of toMaps(String). It reads JSON from an input stream and returns a JsonValue builder without requiring Java classes on the classpath.

      By default, the input stream is closed after reading. To keep it open, configure readOptions.closeStream(false).

      Example:

      
       try (FileInputStream fis = new FileInputStream("data.json")) {
           Map<String, Object> map = JsonIo.toMaps(fis).asClass(Map.class);
       }
       
      Parameters:
      in - the input stream containing JSON; must not be null
      Returns:
      a builder to complete the conversion by specifying the target type
      Throws:
      JsonIoException - if an error occurs during parsing
      IllegalArgumentException - if the input stream is null
    • toMaps

      public static JsonIo.JavaStreamBuilder toMaps(InputStream in, ReadOptions readOptions)
      Parses JSON from an InputStream into a Map graph with custom read options.

      This method combines streaming input with configurable parsing options. The method automatically configures returnAsJsonObjects() mode for class-independent parsing.

      Parameters:
      in - the input stream containing JSON; must not be null
      readOptions - configuration options; if null, defaults will be used
      Returns:
      a builder to complete the conversion by specifying the target type
      Throws:
      JsonIoException - if an error occurs during parsing
      IllegalArgumentException - if the input stream is null
    • toJava

      public static JsonIo.JavaStringBuilder toJava(String json, ReadOptions readOptions)
      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 class
      • asType(TypeHolder) - For converting to a generic type like List<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 used
      readOptions - 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

      public static JsonIo.JavaStreamBuilder toJava(InputStream in, ReadOptions readOptions)
      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 class
      • asType(TypeHolder) - For converting to a generic type like List<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 null
      readOptions - 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

      public static JsonIo.JavaObjectBuilder toJava(JsonObject jsonObject, ReadOptions readOptions)
      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 class
      • asType(TypeHolder) - For converting to a generic type like List<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 null
      readOptions - 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

      public static String formatJson(String json)
      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

      public static <T> T deepCopy(T source, ReadOptions readOptions, WriteOptions writeOptions)
      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 returned
      readOptions - options for controlling deserialization; if null, default options will be used
      writeOptions - 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

      @Deprecated public static <T> T toObjects(String json, ReadOptions readOptions, Class<T> rootType)
      Deprecated.
      Use toJava(String, ReadOptions) with .asClass(Class) instead. This method will be removed in version 5.0.0.

      Example: Person p = JsonIo.toJava(json, opts).asClass(Person.class);

      Converts a JSON string to a Java object of the specified class.
      Type Parameters:
      T - the type of the resulting Java object
      Parameters:
      json - the JSON string to parse
      readOptions - options for controlling the parsing; if null, default options will be used
      rootType - the class to convert the JSON to
      Returns:
      an instance of the specified class populated from the JSON
    • toObjects

      @Deprecated public static <T> T toObjects(InputStream in, ReadOptions readOptions, Class<T> rootType)
      Deprecated.
      Use toJava(InputStream, ReadOptions) with .asClass(Class) instead. This method will be removed in version 5.0.0.

      Example: Person p = JsonIo.toJava(stream, opts).asClass(Person.class);

      Converts JSON from an InputStream to a Java object of the specified class.
      Type Parameters:
      T - the type of the resulting Java object
      Parameters:
      in - the input stream containing JSON
      readOptions - options for controlling the parsing; if null, default options will be used
      rootType - the class to convert the JSON to
      Returns:
      an instance of the specified class populated from the JSON
    • toObjects

      @Deprecated public static <T> T toObjects(JsonObject jsonObject, ReadOptions readOptions, Class<T> rootType)
      Deprecated.
      Use toJava(JsonObject, ReadOptions) with .asClass(Class) instead. This method will be removed in version 5.0.0.

      Example: Person p = JsonIo.toJava(jsonObj, opts).asClass(Person.class);

      Converts a JsonObject (Map representation) to a Java object of the specified class.
      Type Parameters:
      T - the type of the resulting Java object
      Parameters:
      jsonObject - the JsonObject to convert
      readOptions - options for controlling the conversion; if null, default options will be used
      rootType - the class to convert the JsonObject to
      Returns:
      an instance of the specified class populated from the JsonObject
    • main

      public static void main(String[] args)
      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)