Jackson injection learning reference

Source: Internet
Author: User

(1) beginner
We start with several simple application scenarios: Renaming attributes, ignoring attributes, and modifying the types used by attributes.
Note: The following example only shows the field properties. Annotations can also be used in member methods (getter/setter.
① Annotation used for Attribute rename
One of the most common usage methods is to change the JSON name used by a member attribute, for example:

Public class name {
@ Jsonproperty ("firstname ")
Public String _ first_name;
}

The following JSON data result is generated:
{"Firstname": "Bob "}

Instead:
{"_ First_name": "Bob "}

② Annotation used to ignore attributes
Sometimes pojo includes some attributes that you do not want to output. In this case, you can perform the following operations:
Public class value {
Public int value;
@ Jsonignore public int internalvalue;
}

The JSON data result is as follows:
{"Value": 42}

Alternatively, you may ignore some attributes obtained from JSON data. If so, you can use:
@ Jsonignoreproperties ({"extra", "uselessvalue "})
Public class value {
Public int value;
}

In this way, JSON data like the following can be processed:
{"Value": 42, "extra": "fluffy", "uselessvalue":-13}

Finally, you can even simply ignore all the "extra" attributes obtained from JSON (because there is no fully matched pojo in the application. You can add the following code to complete this operation:
@ Jsonignoreproperties (ignoreunknown = true)
Public class pojowithany {
Public int value;
}

③ Annotations used when selecting more/less (more/less) specified types (specific types)
In some cases, when Jackson reads or outputs a member attribute, the selected type may not be what you want:
• When reading (deserialization), the declared type (declared type) may be a basic type (general type), but you know exactly the implementation type to be used: that is to say, we need to deserialize the generated object to implement the type );
• When outputting (serialization), Jackson uses the specified runtime type by default. However, you may not want to output all the information of that type, it is only the information contained in its parent type.
In these application scenarios, you can use the following annotations for processing:
Public class valuecontainer {
// Although the type used in the Code is 'value', the type of the object we want to obtain after reading the JSON is 'valueimpl'
@ Jsondeserialize (as = valueimpl. Class)
Public value;

// Although the runtime type may be 'advancedtype', we do want to serialize it.
// Be 'basictype' (basic type). There are two processing methods:
@ Jsonserialize (as = basictype. Class)
// Or we can do this: @ jsonserialize (Typing = typing. Static)
Public basictype another;
}

(2) Intermediate
① Use the constructor or factory Method
By default, Jackson tries to use the "default" Constructor (No parameter constructor) of the corresponding class when an instance of the corresponding class is created by JSON data ). However, you can choose to use another constructor or a static factory method to create an instance. To complete this operation, you need to use the @ jsoncreator annotation. You may also need to use the @ jsonproperty annotation to bind a name to the parameter (arguments.
Public class ctorpojo {
Private Final int _ x, _ y;

@ Jsoncreator
Public ctorpojo (@ jsonproperty ("X") int X, @ jsonproperty ("Y") int y ){
_ X = X;
_ Y = y;
}
}

In the same way, you can use @ jsoncreator on the static factory method. However, there is an alternative, called the "Authorization" Builder ("delegating" creator ):

Public class delegatingpojo {
Private Final int _ x, _ y;

@ Jsoncreator
Public delegatingpojo (Map <string, Object> delegate ){
_ X = (integer) Delegate. Get ("X ");
_ Y = (integer) Delegate. Get ("Y ");
}
}

The difference is that the builder method can have only one parameter, and the parameter must not (must not) add @ jsonproperty annotation.

② Process polymorphism (polymorphic types)
If the object you want to read or output has many possible sub-types (that is, polymorphism), you may need to add some type information. Jackson needs this information in deserialization (Reading JSON data and generating corresponding objects) to correctly read the object type. You can add the @ jsontypeinfo Annotation on the "Basic Type" to complete the operation:
// Store the Java class name ("com. myempl. implclass") to an attribute named "class" in JSON.
@ Jsontypeinfo (use = ID. Class, include = As. property, property = "class ")
Public abstract class baseclass {
}

Public class impl1 extends baseclass {
Public int X;
}

Public class impl2 extends baseclass {
Public string name;
}

Public class pojowithtypedobjects {
Public list <baseclass> items;
}

In this way, the serialized JSON format is as follows:
{"Items ":[
{"Class": "impl2", "name": "Bob "},
{"Class": "impl1",: "x": 13}
]}

Note: many other configurations can be configured in this annotation. For details, refer:
• Javadocs
• Introduction to polymorphism type processing I (ntro to polymorphic type handling)


③ Reset the automatic discovery of attributes (changing property auto-detection)
Jackson's default property discovery rules will find the following attributes:
• All public-modified fields (member variables );
• All public-modified getters (such as the "getxxx ()" method );
• All public-modified setter methods (such as "setxxx (value)"), whether visible or invisible.
However, you can use the annotation @ jsonautodetect to change the visibility level. If you want to automatically discover all fields (just like the operations performed in the gson package), you can do this:
@ Jsonautodetect (fieldvisibility = jsonautodetect. Visibility. Any)
Public class pojowithfields {
Private int value;
}
Alternatively, you want to disable automatic discovery of all fields:
@ Jsonautodetect (fieldvisibility = jsonautodetect. Visibility. None)
Public class pojowithnofields {
// Will not be serialized unless there is another accessible "getvalue" Method
Public int value;
}

Jackson injection learning reference

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.