Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the JSON Configure () method in Jackson

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to use the JSON Configure () method in Jackson". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical.

Jackson is the currently widely used open source framework of Java for serializing and deserializing json.

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

The default value of the feature name description, AUTO_CLOSE_SOURCE, automatically turns off incoming InputStream or ReadertrueALLOW_COMMENTS to allow Java/C++-style comments in JSON. FalseALLOW_YAML_COMMENTS allows the use of YAML-style annotations in JSON. False

ALLOW_UNQUOTED_FIELD_NAMES allows you to write fields false without quotation marks

ALLOW_SINGLE_QUOTES allows the use of apostrophes and characters'\ 'instead of standard quotation marks false

STRICT_DUPLICATE_DETECTION throws an exception false if a duplicate field is found

IGNORE_UNDEFINED is used if the definition of the attribute contained in the input is not found. False does not work in the case of JSON parsing

INCLUDE_SOURCE_IN_LOCATION contains source reference information in JsonLocation. If this feature is disabled, UNKNOWN locationtrue will be printed

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): the default value of the feature name description, AUTO_CLOSE_TARGET, automatically closes the incoming InputStream or ReadertrueAUTO_CLOSE_JSON_CONTENT. If the generator is closed, it determines how to handle JsonToken.START_ARRAY or JsonToken.START_OBJECT. If enabled, these elements are automatically closed; if disabled, no specific action is performed true

FLUSH_PASSED_TO_STREAM will have the same effect as flush () in OutputStream or Writer if calling JsonGenerator#flush is enabled true

WRITE_BIGDECIMAL_AS_PLAIN will use BigDecimal.toPlainString () to write BigDecimal as plain text falseSTRICT_DUPLICATE_DETECTION. If a duplicate field is found, an exception false is thrown.

IGNORE_UNKNOWN throws a JsonProcessingException if it has no information about the required fields. Invalid when serializing JSON. False

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 (123345353456700.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, the root value is wrapped. This feature is mainly used for JAXB compatibility.

If you disable JSON, it will look like this:

{"name": "Ali Z"}

If JSON is enabled, it will look like this:

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

The output JSON string is indented.

If you disable JSON, it will look like this:

{"name": "Ali Z"}

If JSON is enabled, it will look like this:

{"name": "Ali Z"} false

FAIL_ON_EMPTY_BEANS throws an exception if it does not have an accessor for a field like getter. If trueFAIL_ON_SELF_REFERENCES detects a direct self-reference in a POJO object, it throws a Jackson-specific exception. Note that if it is disabled, it may throw a StackOverflowErrortrue

If disabled, the original exception is thrown. False

FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS will throw an exception if the object has type information but it is marked @ JsonUnwrapped. True will be ignored if type information is disabled

WRITE_SELF_REFERENCES_AS_NULL writes the self-directed citation as null. Notice that the SerializationFeature.FAIL_ON_SELF_REFERENCES configuration is disabled. False

If CLOSE_CLOSEABLE is enabled, pass the close () stream to writeValue. If you want to disable this feature, you should also pay attention to JsonGenerator.Feature.AUTO_CLOSE_TARGET configuration false.

If disabled, ISO-8601 will be used for serialization (for example: 2021-06-20T10:22:34.364+00:00) false

WRITE_DATES_WITH_ZONE_ID

If enabled, time zone information is included. For example:

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

WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS

If enabled, char [] will be used as the JSON array

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

If writing it as a substring is disabled

{"surname": "Zhagparov"} false

WRITE_ENUMS_USING_TO_STRING

These two configurations configure how enumerations are serialized to JSON.

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

{"permissionEnum": "Administrator"} false

WRITE_ENUMS_USING_INDEX

If you disable WRITE_ENUMS_USING_TO_STRING and enable WRITE_ENUMS_USING_INDEX, it will serialize the enumeration using Enum.ordinal ()

{"permissionEnum": 0} false

WRITE_ENUM_KEYS_USING_INDEX

If enabled, it will use Enum.ordinal () to serialize enumerations used in Map into keys

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

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

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

WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED

If enabled, List containing an element is not converted to an JSON array

{"stringList": "Ali Z"}

If disabled, it converts List with one element to an JSON array

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

WRITE_DATE_TIMESTAMPS_AS_NANOOSECONDS

If enabled, a date-time stamp is written in nanoseconds.

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

If disabled

{"date": [2021 date 6, 20, 14, 17, 12, 9900000]} true

If ORDER_MAP_ENTRIES_BY_KEYS is enabled, the Map entries are sorted by pressing the key before serialization. If disabled, sorting is not performed. False

If EAGER_SERIALIZER_FETCH is enabled, ObjectWriter will try eagerly to get the necessary JsonSerializer-s. True

USE_EQUALITY_FOR_OBJECT_ID

If enabled, the Object.equal () method is used as the object identity.

If disabled, the true JVM level identity is used as the object identity.

False

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 the floating point to BigDecimal If disabled, it will be deserialized to Double. If falseUSE_BIG_INTEGER_FOR_INTS is enabled and the field type is Object or Number, it deserializes non-floating point numbers to BigInteger. If disabled, the most compact variants are used. If falseUSE_LONG_FOR_INTS is enabled and the field type is Object or Number, it will deserialize non-floating point numbers to Long;. If disabled, it will use the most compact variant. If falseUSE_JAVA_ARRAY_FOR_JSON_ARRAY is enabled and the field type is unknown, for example, Object,Jackson will deserialize the JSON array to Object []; if disabled, deserialize to ListfalseFAIL_ON_UNKNOWN_PROPERTIES. If enabled, Jackson will throw an exception if an unknown attribute is found. If disabled, such fields will be ignored. TrueFAIL_ON_NULL_FOR_PRIMITIVES if enabled, Jackson throws an exception if JSON contains a null value of the original type. If you disable the default values (such as 0.0, 0, etc.) will be used. False

FAIL_ON_NUMBERS_FOR_ENUMS if enabled, Jackson throws an exception if JSON contains numeric values for enumerations. If this value is disabled, the false will match Enum.ordinal ().

If FAIL_ON_READING_DUP_TREE_KEY is enabled, it will fail if a duplicate tree key is found. If disabled, no exception is thrown, and the subsequent value overrides the previous value. False

If FAIL_ON_IGNORED_PROPERTIES is enabled and JSON contains values that are explicitly marked as negligible, an exception is thrown. If disabled, these fields are ignored. False

If FAIL_ON_MISSING_CREATOR_PROPERTIES is enabled, Jackson will throw an exception if the JSON data field is not described in POJO. If disabled, null is set for unknown fields. False

If FAIL_ON_NULL_CREATOR_PROPERTIES is enabled, an exception is thrown if one or more fields are passed as null to the constructor or static factory method. If disabled, such cases are ignored. False

If disabled, the original exception is thrown. True

ACCEPT_SINGLE_VALUE_AS_ARRAY accepts a single value as an array if Jackson is enabled. If disabled, an exception is thrown. False

If UNWRAP_SINGLE_VALUE_ARRAYS is enabled, it unpacks a single array of values and deserializes it to the appropriate data type. If disabled, an exception is thrown. False

UNWRAP_ROOT_VALUE

If enabled, it unpacks the root value. This means that it will accept such JSON.

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

As

{"name": "Ali Z"} false

ACCEPT_EMPTY_STRING_AS_NULL_OBJECT

If enabled, for empty strings, Jackson will not fail if it does not match the POJO field data type

Public static class Person {private int age;}

And JSON look like that.

{"age": ""}

Jackson will set the null instead of throwing an exception.

False

ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT

If enabled, Jackson will not fail if it does not match the POJO field data type, for empty strings

Public static class Person {private int age;}

And JSON look like that.

{"age": []}

Jackson will set the null instead of throwing an exception.

False

ACCEPT_FLOAT_AS_INT, if enabled, converts floating-point numbers to non-floating-point numbers (such as Long, long, int, and so on) by truncating numbers. If trueREAD_ENUMS_USING_TO_STRING is enabled, it deserializes the Enum using a string. If disabled, Enum.ordinal (); false will be used

If READ_UNKNOWN_ENUM_VALUES_AS_NULL is enabled, it deserializes unknown enumerated values to null. If disabled, an exception will be thrown. False

If READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE is enabled, it is set to use an unknown enumerated value predefined with the @ JsonEnumDefaultValue value. If disabled, it throws an exception. False

If READ_DATE_TIMESTAMPS_AS_NANOOSECONDS is enabled, Jackson will expect to write timestamps in nanoseconds. If disabled, the timestamp is expected to be in milliseconds. True

If ADJUST_DATES_TO_CONTEXT_TIME_ZONE is enabled, it adjusts the date attribute time zone. If disabled, adjustments are made only if the value itself does not contain a time zone. True

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 } @ Override public String toString () {return "Person {" + "age=" + age +'}';} at this point, I believe you have a better understanding of "how to use the JSON Configure () method in Jackson. You might as well do it in practice!" Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report