DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Jackson vs Gson: Edge Cases in JSON Parsing for Java Apps
  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • Lambda-Driven API Design: Building Composable Node.js Endpoints With Functional Primitives
  • The Update Problem REST Doesn't Solve

Trending

  • LLM-Powered Deep Parsing for Industrial Inventory Search
  • A 5-Step SOC Guide That Meets RBI Expectations and Strengthens Security Operations
  • Self-Hosted Inference Doesn’t Have to Be a Nightmare: How to Use GPUStack
  • Why We Chose Iceberg Over Delta After Evaluating Both at Scale
  1. DZone
  2. Coding
  3. Languages
  4. The Configure() Method in Jackson in JSON

The Configure() Method in Jackson in JSON

In this tutorial, learn how to use the configure() method in Jackson in JSON. Read on to see how this tutorial can help you!

By 
Ali ZHAGPAROV user avatar
Ali ZHAGPAROV
·
Aug. 20, 21 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
15.8K Views

Join the DZone community and get the full member experience.

Join For Free

Configure method allows you to add additional behavior for ObjectMapper.

1. #configure(JsonParser.Feature, boolean):

Feature name Description Default Value
AUTO_CLOSE_SOURCE Will automatically close passed InputStream or Reader true
ALLOW_COMMENTS Allow using of Java/C++ style comments in JSON.  false
ALLOW_YAML_COMMENTS Allows using of YAML-style comments in JSON.  false
ALLOW_UNQUOTED_FIELD_NAMES  Allows to write fields without quotes false
ALLOW_SINGLE_QUOTES Allows using apostrophe, character '\'' instead of the standard quotes false
STRICT_DUPLICATE_DETECTION Throw exception if duplicated field found false
IGNORE_UNDEFINED Used in case if no definition is found for a property that input content contains. Has no effect in the case of JSON parsing  false
INCLUDE_SOURCE_IN_LOCATION Include source reference information in JsonLocation. If the feature is disabled prints UNKNOWN location  true


Java:

public class StrictDuplicateMapper {
    public static void main(String[] args) throws JsonProcessingException {
        String json = "{" +
                  "\"name\":\"Ali Z\", " +
                  "\"name\":\"Ali Zh\"" + // will throw exception because that field is duplicated
                "}";

        ObjectMapper mapper = new ObjectMapper()
                .configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true)
                .enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);// another way of enabling featur
        mapper.readValue(json, Person.class);
    }

    public static class Person {
        private String name;

        @JsonCreator
        public Person(@JsonProperty("name") String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}


2. ObjectMapper#configure(JsonGenerator.Feature, boolean):

Feature name Description Default value
AUTO_CLOSE_TARGET Will automatically close passed InputStream or Reader  true
AUTO_CLOSE_JSON_CONTENT  Determines what to do with JsonToken.START_ARRAY or JsonToken.START_OBJECT if the generator is closed. If enabled, such elements are automatically closed; if disabled, nothing specific is done  true
FLUSH_PASSED_TO_STREAM if enabled calling JsonGenerator#flush will have the same effect as flush() in OutputStream or Writer   true
WRITE_BIGDECIMAL_AS_PLAIN Will write BigDecimal as plain text using the BigDecimal.toPlainString()   false
STRICT_DUPLICATE_DETECTION  Throw exception if duplicated field found  false
IGNORE_UNKNOWN Will throw  JsonProcessingException if there is no information about the required field. Has no effect when serializing JSON.  false


Java:

public class JsonGeneratorExample {

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper()
                .configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true);

        Person person = new Person();
        person.setAge(BigDecimal.valueOf(12334535345456700.12345634534534578901));

        String json = mapper.writeValueAsString(person);

        System.out.println(json);
    }

    public static class Person {
        private BigDecimal age;

        public BigDecimal getAge() {
            return age;
        }

        public void setAge(BigDecimal age) {
            this.age = age;
        }
    }
}

3. ObjectMapper#configure(SerializationFeature, boolean):

Feature name Description Default value
WRAP_ROOT_VALUE

if enabled will wrap root value. The feature is mostly intended for JAXB compatibility.

if disabled JSON will look like that:

{"name":"Ali Z"}

if enabled JSON will look like that:

{"Person":{"name":"Ali Z"}}
false
INDENT_OUTPUT

Will indent output JSON string.

if disabled JSON will look like that:

{"name":"Ali Z"}

if enabled JSON will look like that:

{
 "name" : "Ali Z"
}
false
FAIL_ON_EMPTY_BEANS Will throw an exception in the case there are no accessors for fields like getters.   true
FAIL_ON_SELF_REFERENCES Will throw a Jackson-specific exception if direct self-reference is detected in a POJO object. Pay attention in case if it's disabled it may throw StackOverflowError  true
WRAP_EXCEPTIONS If enabled, Jackson will catch exceptions are thrown during serialization and wrap it with Jackson exception by providing additional information. If disabled will throw the original exception.  false
FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS Will throw an exception, In case the object has type information but it was marked with          @JsonUnwrapped. if disabled type information will be ignored  true
WRITE_SELF_REFERENCES_AS_NULL Writes self-directed references as null.  Pay attention that SerializationFeature.FAIL_ON_SELF_REFERENCES configuration is disabled. false
CLOSE_CLOSEABLE if enabled, will close() stream passed to writeValue. if you want to disable that feature also pay attention to JsonGenerator.Feature.AUTO_CLOSE_TARGET configuration  false
WRITE_DATES_AS_TIMESTAMPS if enabled, Jackson will serialize java.util.Date(also subtype) used as a key in a Map will be serialized as a timestamp. if disable, will serialized using ISO-8601 (example: 2021-06-20T10:22:34.364+00:00) false
WRITE_DATES_WITH_ZONE_ID

if enabled, includes timezone information. For example:

2011-12-03T10:15:30+01:00[Europe/Paris]
false
WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS

If enabled will wright char[] as JSON arrays,

{"surname":["Z","h","a","g","p","a","r","o","v"]}

if disabled will write it as a son string

{"surname":"Zhagparov"}
false
WRITE_ENUMS_USING_TO_STRING

These two configurations configure the way enums will be serialized into JSON.

If WRITE_ENUMS_USING_TO_STRING is enabled and WRITE_ENUMS_USING_INDEX is disabled, it will serialize enums using toString()

{"permissionEnum":"ADMIN"}
false
WRITE_ENUMS_USING_INDEX

If WRITE_ENUMS_USING_TO_STRING is disabled and WRITE_ENUMS_USING_INDEX is enabled, it will serialize enums using Enum.ordinal()

{"permissionEnum":0}
false
WRITE_ENUM_KEYS_USING_INDEX

If enabled, it will serialize enums used in Map as key using Enum.ordinal()

{"permissionEnum":{"0":"admin"}}

If disabled, it will serialize enums using Enum.toString()

{"permissionEnum":{"ADMIN":"admin"}}
false
WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED

If enabled, won't convert List with one element into JSON array

{"stringList":"Ali Z"}

If disabled, it will convert List with one element into JSON array

{"stringList":["Ali Z"]}
false
WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS

if enabled, will write date timestamps in nanoseconds.

{"date":[2021,6,20,14,16,48,260]}

if disabled,

{"date":[2021,6,20,14,17,12,990000000]}
true 
ORDER_MAP_ENTRIES_BY_KEYS  if enabled, will sort Map entries by key before serialization. Won't perform sorting, if disabled.  false
EAGER_SERIALIZER_FETCH if enabled, ObjectWriter will try to eagerly fetch the necessary JsonSerializer-s.   true
USE_EQUALITY_FOR_OBJECT_ID

if enabled, will use Object.equal() method as an object identity.

if disabled, will use true JVM-level identity as an object identity. 

false


Java:


public class JsonSerializationFeatureExample {

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper()
                .configure(SerializationFeature.WRAP_ROOT_VALUE, true)
                .configure(SerializationFeature.INDENT_OUTPUT, true);

        Person person = new Person();
        person.setName("Ali Z");

        String json = mapper.writeValueAsString(person);

        System.out.println(json);
    }

    public static class Person {
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}

4. ObjectMapper#configure(DeserializationFeature, boolean):

Feature name Description Default value
USE_BIG_DECIMAL_FOR_FLOATS if enabled and the field type is Object or Number it will deserialize floating-point numbers as BigDecimal; if disabled, it will be deserialized as Double.  false
USE_BIG_INTEGER_FOR_INTS if enabled and the field type is Object or Number it will deserialize non-floating-point numbers as BigInteger. if disabled, the most compact variant will be used.  false
USE_LONG_FOR_INTS if enabled and the field type is Object or Number it will deserialize non-floating-point numbers as Long; if disabled, the most compact variant will be used.  false
USE_JAVA_ARRAY_FOR_JSON_ARRAY if enabled and the field type is unknown for example Object, Jackson will deserialize JSON array as Object[]; if disabled, will deserialize as List<Object>  false
FAIL_ON_UNKNOWN_PROPERTIES if enabled, Jackson will throw an exception if the unknown property is found. if disabled will ignore such a field.  true
FAIL_ON_NULL_FOR_PRIMITIVES if enabled, Jackson will throw an exception if JSON contains a null value for the primitive type. if disabled default values (like 0.0, 0, etc.) will be used.  false
FAIL_ON_NUMBERS_FOR_ENUMS if enabled, Jackson will throw an exception if JSON contains a number value for the enum. if disabled such value will be matched with Enum.ordinal()  false
FAIL_ON_READING_DUP_TREE_KEY if enabled, will fail if find a duplicated tree key.  if disabled, no exception is thrown and the later value overwrites the earlier value.  false
FAIL_ON_IGNORED_PROPERTIES if enabled and JSON contains values that are explicitly marked as ignorable, will be thrown an exception. if disabled, such fields will be ignored.  false
FAIL_ON_MISSING_CREATOR_PROPERTIES if enable, Jackson will throw an exception if JSON data field doesn't describe in POJO. If disabled will set null for unknown fields. false
FAIL_ON_NULL_CREATOR_PROPERTIES If enabled, will throw an exception if one or more field was passed as null to the constructor or static factory method. will ignore such cases, if disabled. false
WRAP_EXCEPTIONS If enabled, Jackson will catch exceptions are thrown during deserialization and wrap it with Jackson exception by providing additional information. If disabled will throw the original exception.  true
ACCEPT_SINGLE_VALUE_AS_ARRAY if enable Jackson will accept a single value as an array. If disabled, then the exception will be thrown.  false
UNWRAP_SINGLE_VALUE_ARRAYS If enabled, it will unwrap a single value array and deserialize it into the corresponding datatype. If disabled, the exception will be thrown.  false
UNWRAP_ROOT_VALUE

If enabled, it will unwrap the root value. It means it will accept such JSON

{"Person":{"name":"Ali Z"}}

as

{"name":"Ali Z"}
false
ACCEPT_EMPTY_STRING_AS_NULL_OBJECT

If enabled, Jackson won't fail in case there is a mismatch with POJO field data type, for empty String

public static class Person {
    private Integer age;
}

and JSON looks like that 

{"age":""}

Jackson will set null instead of throwing an exception.

false
ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT

If enabled, Jackson won't fail in case there is a mismatch with POJO field data type, for empty String

public static class Person {
   private Integer age;
}

and JSON looks like that

{"age":[]}

Jackson will set null instead of throwing an exception.

false
ACCEPT_FLOAT_AS_INT if enabled, will convert floating-point numbers into a non-floating-point numbers (like Long, long, int, etc.) by truncating numbers.  true
READ_ENUMS_USING_TO_STRING If enabled, it will deserialize Enum using to string. if disabled, will use Enum.ordinal();  false
READ_UNKNOWN_ENUM_VALUES_AS_NULL If enabled, it will deserialize the unknown enum value as null. If disabled will throw an exception.  false
READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE If enabled, it will set to unknown enum value predefined with @JsonEnumDefaultValue value. If disabled, it will throw an exception.  false
READ_DATE_TIMESTAMPS_AS_NANOSECONDS If enabled, Jackson will expect that timestamp written in nanoseconds. If disabled, timestamp expected in milliseconds.  true
ADJUST_DATES_TO_CONTEXT_TIME_ZONE If enabled, it will adjust a date property timezone. if disabled, will only adjust if the value doesn't contain a time zone by itself. true


Java:

public class DeserializeExample {
    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper()
                .configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, true)
                .enable(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES);

        Person person = mapper.readValue("{}", Person.class);
    }


    public static class Person {
        private Integer age;

        @JsonCreator
        public Person(@JsonProperty("age") Integer age) {
            this.age = age;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "Person{" +
                    "age=" + age +
                    '}';
        }
    }
}


JSON Jackson (API)

Opinions expressed by DZone contributors are their own.

Related

  • Jackson vs Gson: Edge Cases in JSON Parsing for Java Apps
  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • Lambda-Driven API Design: Building Composable Node.js Endpoints With Functional Primitives
  • The Update Problem REST Doesn't Solve

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook