[Java] Jackson notes

Source: Internet
Author: User

The Jackson (http://jackson.codehaus.org) library is an open source JSON format parsing tool based on the Java language. Compared to other libraries Javajson parsing, such as Json-lib, Gson packages, Jackson has the following advantages:

Fully functional, provide a variety of modes of JSON parsing, "object binding" easy to use, the use of annotations package can provide a lot of convenience for our development.

Performance is high, and the parsing efficiency of the "stream mode" exceeds the majority of similar JSON packages.

Jackson's main package

The jackson-core--core package (required) provides an API based on "stream mode" parsing. Core package: Jsonpaser (JSON stream read), Jsongenerator (JSON stream output).

The jackson-databind--data binding package (optional) provides APIs based on the object binding and tree model. Data binding Package: Objectmapper (build tree mode and object binding mode), Jsonnode (tree node).

The jackson-annotations--annotation package (optional) provides annotation functionality.

jackson-datatype-joda-2.1.5.jar--Date Conversion

Jackson notes 1. Rename the property, ignore the property, and modify the type used by the property.

① annotations used when renaming a property

One of the most common ways to use this is to change the JSON name used by a member property. For example: Class Name {@JsonProperty ("firstName") public String _first_name;}

② ignore annotations used by attributes

Sometimes Pojo includes some properties that you do not want to output, in which case you can do the following:

public class Value {
public int value;
@JsonIgnore public int internalvalue;
}

Or, you might ignore some of the properties you get from JSON data, and if so, you can use:
@JsonIgnoreProperties ({"Extra", "Uselessvalue"})
public class Value {
public int value;
}

Or, more violently, ignore all the "extra" attributes obtained from JSON (due to pojo that do not have an exact match in the app).

@JsonIgnoreProperties (Ignoreunknown=true)
public class Pojowithany {
public int value;
}

Choose more/less Specific types when using annotations

In some cases, when Jackson reads or outputs a member property, the selected type (type) may not be what you want

@JsonSerialize (As=basictype.class) serializes a type to a specified type

@JsonSerialize (using=customdoubleserialize.class) acts on a property or field to embed our custom code when serializing, such as when serializing a double with a two-bit decimal point behind it.  

@JsonDeserialize acting on a property or field, specifying how to deserialize

@JsonDeserialize (As=valueimpl.class) deserializes a type into a specified type

@JsonDeserialize (using= Customdatedeserialize.class) for embedding our custom code when deserializing

2. Using constructors or Factory methods

By default, when an instance of the corresponding class is created by the JSON data, Jackson attempts to use the class's default constructor (that is, the parameterless constructor). However, you can choose to use a different constructor, or a static factory method, to create an instance. To do this, you need to use the @jsoncreator annotation, and you may also need to use the @jsonproperty annotation for the parameter (arguments) binding name.

publicclass Mybean {  privateint  value;
@JsonCreator Publicmybean (@JsonProperty (int v) { this. Value= V; } Public int return value;}}

Using the same approach, @jsoncreator can be used on static factory methods. However, there is an optional alternative, known as the "authorized" Builder ("Delegating" creator):

publicclass Delegatingpojo {   privatefinalint  _x, _y;   @JsonCreator   Publicdelegatingpojo (Map<String,Object> delegate) {      = (Integer) Delegate.get ("x");       = (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 annotations.

3. Dealing with Polymorphic types

If you want to read and output objects that have many possible subtypes (that is, show polymorphism), you may also need to add some type information. Jackson needed this information when deserializing (reading the JSON data, generating the corresponding object) so that the type of the object could be read correctly. We can do this by adding @jsontypeinfo annotations on the basic type:

@JsonTypeInfo class annotations, when an object with an output operation has multiple subtypes and needs to add type information for the subclass object when deserializing, use this annotation to correctly set the type of the subclass object

@JsonTypeInfo (use=id.class,include=as.property,property= "class") subclass type as an attribute with the property name class

Store the name of the Java class ("Com.myempl.ImplClass") in a property of the JSON named "Class"

@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;
}

Items after serialization have similar results:

{"Items": [
{"Class": "Impl2", "name": "Bob"},
{"Class": "Impl1",: "X": 13}
]}

4. Reset Auto-discovery of attributes (changing property auto-detection)

@JsonAutoDetect

class annotations, specifying attribute discovery rules

Jackson The default property discovery rule will look for properties such as the following:

• All fields that are modified by public (member variables);

• All getters modified by public (i.e., "getXxx ()");

• All public-modified setters (i.e., "setxxx (value)")

@JsonAutoDetect (Fieldvisibility=jsonautodetect.visibility.any)

@JsonAutoDetect (Fieldvisibility=jsonautodetect.visibility.none)

More Annotations View Http://wiki.fasterxml.com/JacksonAnnotations

Original: http://blog.csdn.net/ljhabc1982/article/details/17553095

[Java] Jackson notes

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.