Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Serialization features

Tatu Saloranta edited this pageMay 29, 2020 ·12 revisions

Jackson on/off features: SerializationFeature

Jackson defines a set of features that relate to serialization (writing Java objects as JSON), and that can be changed on per-call basis (by usingObjectWriter). For example:

final ObjectWriter w = objectMapper.writer();// enable one feature, disable anotherbyte[] json = w  .with(SerializationFeature.INDENT_OUTPUT)  .without(FAIL_ON_EMPTY_BEANS.WRAP_EXCEPTIONS)  .writeValueAsBytes(value);

You can also change defaults forObjectMapper, to be used as the base for allObjectWriter instances, usingenable(feature),disable(feature) andconfigure(feature, state) methods.

Settings can be divided in couple of loose categories, as follows.

Generic output features

  • WRAP_ROOT_VALUE (default: false)
    • When enabled, will wrap output in a single-property JSON Object. Name of wrapper property is based on one of:
      • @JsonRootName annotation value, or
      • @XmlRootElement if (and only if) usingJAXB Annotations, or
      • Simple Class name (no package prefix) of the serialized instance (or value type if static typing used or root type specified), if no annotation is specified.
    • Note that this settings does NOT have effect when writing XML since XML ALWAYS requires separate root element (true for Jackson versions2.3 and later)
  • INDENT_OUTPUT (default: false)
    • Controls whether output is indented using the default indentation ("pretty-printing") mechanism (2-space, platform linefeeds) or not.
    • NOTE: not all data formats support indentation: binary formats do not have the concept (they are not human-readable); andCSV has flat structure and can not be "prettified"

Error handling

  • FAIL_ON_EMPTY_BEANS (default: true)
    • Controls whether exception is thrown if no serializer is found for a type (Class); and type has neither getters nor recognized annotations (ones configuredAnnotationIntrospector recognizes, including JAXB Annotations if JAXB introspector used).
  • WRAP_EXCEPTIONS (default: true)
    • Feature that determines whether Jackson code should catch and wrapExceptions (but neverErrors) to add additional information about location (within input) of problem or not.
    • If enabled, most exceptions will be caught and re-thrown (exception specifically being thatjava.io.IOExceptions may be passed as-is, since they are declared as throwable); this can be convenient both in that all exceptions will be checked and declared, and so there is more contextual information. However, sometimes calling application may just want "raw" unchecked exceptions passed as is.

Output life-cycle features

  • CLOSE_CLOSEABLE (default: false)
    • If enabled,ObjectMapper will callclose() and root values that implementjava.io.Closeable; including cases where exception is thrown and serialization does not completely succeed.
    • Can be useful for resource clean up; and specifically allows for building wrappers that can be useful when serializing referential values (like, say, serializing a {{{java.io.File}}} value by reading contents of a file and outputting as JSON String or base64-encoded binary)
  • FLUSH_AFTER_WRITE_VALUE (default: true)
    • Determines whetherJsonGenerator.flush() is automatically called afterObjectMapperswriteValue(JsonGenerator, ...) is called or not (note: does NOT affect methods that do not takeJsonGenerator) -- if true flush() is called; if false, it is not called.
    • Main reason to disable this feature is performance; for network connections flushing may send message earlier than optimal, and with some compressing streams compression block may complete with flush().

Datatype-specific serialization

  • WRITE_DATES_AS_TIMESTAMPS (default: true)
    • Controls whether Date / Time values are to be written out as numeric (64-bit) timestamps (if true) or as Strings. If latter, format used is defined bySerializationConfig.getDateFormat
  • WRITE_DATE_KEYS_AS_TIMESTAMPS (default: false)
    • Feature that determines whetherjava.util.Dates (and sub-types) used asjava.util.Map keys are serialized as timestamps or not. If not, will be serialized as textual (ISO-8601) values.
  • WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS (default: false)
    • Controls how basicchar[] values are serialized: if enabled, they will be serialized as full JSON Arrays, with JSON Strings (of length 1 character) as elements; if disabled (which is the default) as a single JSON String consisting of all characters of the array.
  • WRITE_ENUMS_USING_TO_STRING (default: false)
    • Determines which method is used to determine expected serialization of an Enum (when serialized as String): if false (default), useEnum.name(); if true,Enum.toString().
  • WRITE_ENUMS_USING_INDEX (default: false)
    • Determines whether Enums are to be serialized as integers (true), or Strings (false): if integers,Enum.ordinal() value is used as serialization.
  • WRITE_NULL_MAP_VALUES (default: true)
    • Determines whether Map entries with value null are serialized or not.
  • WRITE_EMPTY_JSON_ARRAYS (default: true)
    • Allows suppressing serialization of empty Collections/arrays.
  • WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED (default: false)
    • Feature to change handling of single-element Arrays,java.util.Collections, so that such arrays/collections are serialized as "unwrapped" elements, not as JSON Arrays.
  • WRITE_BIGDECIMAL_AS_PLAIN (default: false) (since Jackson 2.2)
    • If enabled, will prevent use of scientific notation (use of 'e' in value to normalize scale of mantisaa); if disabled, will use scientific notation when necessary.
  • WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS (default: true) (since Jackson 2.2)
    • Feature that controls whether numeric timestamp values are expected to be written using nanosecond timestamps (enabled) or not (disabled); if disabled, standard millisecond timestamps are assumed.
    • Only newer datatypes (such as Java 8 Date/Time aka JSR-310) support this setting; older Date/Time types (java.util.Date,java.util.Calendar, Joda date/time) do not have resolution to support it.
  • ORDER_MAP_ENTRIES_BY_KEYS (default: false)
    • Feature that determines whetherjava.util.Map entries are first sorted by key before serialization or not: if enabled, additional sorting step is performed if necessary (not necessary forjava.util.SortedMaps), if disabled, no additional sorting is needed.

Other

  • EAGER_SERIALIZER_FETCH (default: true) (sinceJackson 2.1)
    • Feature that determines whetherObjectWriter should try to eagerly fetch necessaryJsonSerializer when possible. This improves performance in cases where similarly configuredObjectWriter instance is used multiple times; and should not significantly affect single-use cases.
    • There should not be any need to normally disable this feature: only consider that if there are actual perceived problems.
  • USE_EQUALITY_FOR_OBJECT_ID (default: false) (sinceJackson 2.3)
    • Feature that determines whether Object Identity is compared using true JVM-level identity of Object (false); or,equals() method.
    • Setting this totrue (to useequals()) is sometimes useful when dealing with Database-bound objects with ORM libraries like Hibernate.

Clone this wiki locally


[8]ページ先頭

©2009-2025 Movatter.jp