Class JsonIo

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

public class JsonIo extends Object
This is the main API for json-io. Use these methods to convert:
  • 1. Input: Java root | JsonObject root Output: JSON
    String json = JsonIo.toJson(JavaObject | JsonObject root, writeOptions)
  • 2. Input: Java root | JsonObject root, Output: JSON -> outputStream
    JsonIo.toJson(OutputStream, JavaObject | JsonObject root, writeOptions)
  • 3. Input: JSON, Output: Java objects | JsonObject
    BillingInfo billInfo = JsonIo.toObjects(String | InputStream, readOptions, BillingInfo.class)
  • 4. Input: JsonObject root, Output: Java objects
    BillingInfo billInfo = JsonIo.toObjects(JsonObject, readOptions, BillingInfo.class)
  • Often, the goal is to get JSON to Java objects and from Java objects to JSON. That is #1 and #3 above.

    For approaches #1 and #2 above, json-io will check the root object type (regular Java class or JsonObject (Map) instance) to know which type of Object Graph it is serializing to JSON.

    There are occasions where you may just want the raw JSON data, without anchoring it to a set of "DTO" Java objects. For example, you may have an extreme amount of data, and you want to process it as fast as possible, and in streaming mode. The JSON specification has great primitives which are universally useful in many languages. In Java that is boolean, null, long [or BigInteger], and double [or BigDecimal], and String.

    When JsonObject is returned [option #3 or #4 above with readOptions.returnAsNativeJsonObjects(), your root value will represent one of:
      JSON object {...}
      JSON array [...]
      JSON primitive (boolean true/false, null, long, double, String).

    {...} JsonObject implements the Map interface and represents any JSON object {...}.

    [...] JsonObject implements the Map interface and the value associated to the @items key will represent the JSON array [...].

    Primitive or JsonObject If the root of the JSON is a String, Number (Long or Double), Boolean, or null, not an object { ... } nor an array { ... }, then it will be a String, long, true, false, null, double or BigDecimal. If the primitive value is wrapped in a JSON object {"value": 10} then it will be returned as a Map (JsonObject).

    If you have a return object graph of JsonObject (Map-of-Maps) and want to turn these into Java (DTO) objects, use #4. To turn the JsonObject graph back into JSON, use option #1 or #2.

Author:
John DeRegnaucourt ([email protected]), Kenny Partlow ([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.
  • Field Details

    • CUSTOM_READER_MAP

      public static final String CUSTOM_READER_MAP
      If set, this maps class ==> CustomReader
      See Also:
    • NOT_CUSTOM_READER_MAP

      public static final String NOT_CUSTOM_READER_MAP
      If set, this indicates that no custom reader should be used for the specified class ==> CustomReader
      See Also:
    • USE_MAPS

      public static final String USE_MAPS
      If set, the read-in JSON will be turned into a Map of Maps (JsonObject) representation
      See Also:
    • UNKNOWN_OBJECT

      public static final String UNKNOWN_OBJECT
      What to do when an object is found and 'type' cannot be determined.
      See Also:
    • FAIL_ON_UNKNOWN_TYPE

      public static final String FAIL_ON_UNKNOWN_TYPE
      Will fail JSON parsing if 'type' class defined but is not on classpath.
      See Also:
    • TYPE_NAME_MAP

      public static final String TYPE_NAME_MAP
      If set, this map will be used when writing @type values - allows short-hand abbreviations type names
      See Also:
    • MISSING_FIELD_HANDLER

      public static final String MISSING_FIELD_HANDLER
      If set, this object will be called when a field is present in the JSON but missing from the corresponding class
      See Also:
    • CLASSLOADER

      public static final String CLASSLOADER
      If set, use the specified ClassLoader
      See Also:
    • MAX_PARSE_DEPTH

      public static final String MAX_PARSE_DEPTH
      Default maximum parsing depth
      See Also:
    • CUSTOM_WRITER_MAP

      public static final String CUSTOM_WRITER_MAP
      If set, this maps class ==> CustomWriter
      See Also:
    • NOT_CUSTOM_WRITER_MAP

      public static final String NOT_CUSTOM_WRITER_MAP
      If set, this maps class ==> CustomWriter
      See Also:
    • DATE_FORMAT

      public static final String DATE_FORMAT
      Set the date format to use within the JSON output
      See Also:
    • ISO_DATE_FORMAT

      public static final String ISO_DATE_FORMAT
      Constant for use as DATE_FORMAT value
      See Also:
    • ISO_DATE_TIME_FORMAT

      public static final String ISO_DATE_TIME_FORMAT
      Constant for use as DATE_FORMAT value
      See Also:
    • TYPE

      public static final String TYPE
      Force @type always
      See Also:
    • PRETTY_PRINT

      public static final String PRETTY_PRINT
      Force nicely formatted JSON output
      See Also:
    • FIELD_SPECIFIERS

      public static final String FIELD_SPECIFIERS
      Set value to a Map<Class, List<String>> which will be used to control which fields on a class are output
      See Also:
    • FIELD_NAME_BLACK_LIST

      public static final String FIELD_NAME_BLACK_LIST
      Set value to a Map<Class, List<String>> which will be used to control which fields on a class are not output. Black list has always priority to FIELD_SPECIFIERS
      See Also:
    • ENUM_PUBLIC_ONLY

      public static final String ENUM_PUBLIC_ONLY
      If set, indicates that private variables of ENUMs are not to be serialized
      See Also:
    • WRITE_LONGS_AS_STRINGS

      public static final String WRITE_LONGS_AS_STRINGS
      If set, longs are written in quotes (Javascript safe)
      See Also:
    • SHORT_META_KEYS

      public static final String SHORT_META_KEYS
      If set, then @type -> @t, @keys -> @k, @items -> @i
      See Also:
    • SKIP_NULL_FIELDS

      public static final String SKIP_NULL_FIELDS
      If set, null fields are not written
      See Also:
    • FORCE_MAP_FORMAT_ARRAY_KEYS_ITEMS

      public static final String FORCE_MAP_FORMAT_ARRAY_KEYS_ITEMS
      If set to true all maps are transferred to the format @keys[],@items[] regardless of the key_type
      See Also:
  • Method Details

    • toJson

      public static String toJson(Object srcObject, WriteOptions writeOptions)
      Convert the passed in Java source object to JSON.
      Parameters:
      srcObject - Java instance to convert to JSON format. Can be a JsonObject that was loaded earlier via .toObjects() with readOptions.returnAsNativeJsonObjects().
      writeOptions - Feature options settings to control the JSON output. Can be null, in which case, default settings will be used.
      Returns:
      String of JSON that represents the srcObject in JSON format.
      Throws:
      JsonIoException - A runtime exception thrown if any errors happen during serialization
    • toJson

      public static void toJson(OutputStream out, Object source, WriteOptions writeOptions)
      Convert the passed in Java source object to JSON. If you want a copy of the JSON that was written to the OutputStream, you can wrap the output stream before calling this method, like this:

      ByteArrayOutputStream baos = new ByteArrayOutputStream(originalOutputStream);
      JsonIo.toJson(baos, source, writeOptions);
      baos.flush();
      String json = new String(baos.toByteArray(), StandardCharsets.UTF_8);

      Parameters:
      out - OutputStream destination for the JSON output. The OutputStream will be closed by default. If you don't want this, set writeOptions.closeStream(false). This is useful for creating NDJSON, where multiple JSON objects are written to the stream, separated by a newline.
      source - Java instance to convert to JSON format. Can be a JsonObject that was loaded earlier via .toObjects() with readOptions.returnAsNativeJsonObjects().
      writeOptions - Feature options settings to control the JSON output. Can be null, in which case, default settings will be used.
      Throws:
      JsonIoException - A runtime exception thrown if any errors happen during serialization
    • toObjects

      public static <T> T toObjects(String json, ReadOptions readOptions, Class<T> rootType)
      Convert the passed in JSON to Java Objects.
      Parameters:
      json - String containing JSON content.
      readOptions - Feature options settings to control the JSON processing. Can be null, in which case, default settings will be used.
      rootType - Class of the root type of object that will be returned. Can be null, in which case a best-guess will be made for the Class type of the return object. If it has an @type meta-property that will be used, otherwise the JSON types { ... } will return a Map, [...] will return Object[] or Collection, and the primitive types will be returned (String, long, Double, boolean, or null).
      Returns:
      rootType Java instance that represents the Java equivalent of the passed in JSON string.
      Throws:
      JsonIoException - A runtime exception thrown if any errors happen during serialization
    • toObjects

      public static <T> T toObjects(InputStream in, ReadOptions readOptions, Class<T> rootType)
      Convert the passed in JSON to Java Objects.
      Parameters:
      in - InputStream bringing JSON content. By default, it will be closed. If you don't want it closed after reading, set readOptions.closeStream(false).
      readOptions - Feature options settings to control the JSON processing. Can be null, in which case, default settings will be used.
      rootType - Class of the root type of object that will be returned. Can be null, in which case a best-guess will be made for the Class type of the return object. If it has a @type meta-property that will be used, otherwise a JsonObject will be returned.
      Returns:
      rootType Java instance that represents the Java equivalent of the JSON input. If the returnType() on ReadOptions is set to ReturnType.JSON_OBJECTS, then the root return value will be a JsonObject, which can represent a JSON object {...}, a JSON array [...], or a JSON primitive. JsonObject has .is*() methods on it to determine the type of object represented. If the type is a JSON primitive, use .getValue() on JSON object to obtain the primitive value.
      Throws:
      JsonIoException - A runtime exception thrown if any errors happen during serialization
    • toObjects

      public static <T> T toObjects(JsonObject jsonObject, ReadOptions readOptions, Class<T> rootType)
      Convert a root JsonObject (Map) that represents parsed JSON, into an actual Java object. This Map-of-Map roots would have come from a prior API call to JsonIo.toObjects(String) or JsonIo.toObjects(InputStream) with the new ReadOptionBuilder().returnAsJsonObjects() option set. This option allows you to read any JSON because it is only stuffing it into Maps, not Java objects. This API can take this Map-of-Maps representation of JSON, and then recreate the Java objects from it. It can do this, because the Map-of-Map's it returns are subclasses of Java's Map that contain a 'type' field, and it will use this to recreate the correct Java object when written via toJson and the Map (JsonObject) is passed as the root.
      Parameters:
      readOptions - ReadOptions to control the feature options. Can be null to take the defaults.
      rootType - The class that represents, in Java, the root of the underlying JSON from which the JsonObject was loaded.
      Returns:
      a typed Java instance object graph.
    • formatJson

      public static String formatJson(String json)
      Format the passed in JSON into multi-line, indented format, commonly used in JSON online editors.
      Parameters:
      json - String JSON content.
      Returns:
      String JSON formatted in human-readable, standard multi-line, indented format.
    • deepCopy

      public static <T> T deepCopy(Object source, ReadOptions readOptions, WriteOptions writeOptions)
      Copy an object graph using JSON.
      Parameters:
      source - Object root object to copy
      readOptions - ReadOptions feature settings. Can be null for default ReadOptions.
      writeOptions - WriteOptions feature settings. Can be null for default WriteOptions.
      Returns:
      A new, duplicate instance of the original.
    • main

      public static void main(String[] args)
      Call this method to see all the conversions offered.
      Parameters:
      args - String[] of command line arguments
    • getReadOptionsBuilder

      @Deprecated public static ReadOptionsBuilder getReadOptionsBuilder(Map<String,Object> optionalArgs)
      Deprecated.
      - This exists to show how the old Map<String, Object> options are crreated using ReadOptionsBuilder.
      Convert an old-style Map of options to a ReadOptionsBuilder. It is not recommended to use this API long term, however, this API will be the fastest route to bridge an old installation using json-io to the new API.
      Parameters:
      optionalArgs - Map of old json-io options
      Returns:
      ReadOptionsBuilder
    • getWriteOptionsBuilder

      @Deprecated public static WriteOptionsBuilder getWriteOptionsBuilder(Map<String,Object> optionalArgs)
      Deprecated.
      - This exists to show how the old Map<String, Object> options are crreated using WriteptionsBuilder.
      Convert an old-style Map of options to a WriteOptionsBuilder. It is not recommended to use this API long term, however, this API will be the fastest route to bridge an old installation using json-io to the new API.
      Parameters:
      optionalArgs - Map of old json-io options
      Returns:
      WriteOptionsBuilder