Jackson Use (iii)----use annotations

Source: Internet
Author: User
Tags json serialization wrapper

Jackson has provided us with a series of annotations in practical application, which improves the flexibility of development, and describes some of the most common annotations

Reference: http://blog.csdn.net/sdyy321/article/details/40298081


1. @JsonIgnoreProperties

This annotation is a class annotation that ignores some properties in a Java bean when JSON is serialized. Both serialization and deserialization are affected.

2. @JsonIgnore

Word annotations are used in properties or methods, as well as @jsonigonreproperties. Returns NULL when deserializing, how the field is marked with Jsonignore

3. @JsonFormat

In the properties and methods, it is convenient to format the conversion, such as converting the date to the pattern we want @jsonformat (pattern = "Yyyy-mm-dd hh-mm-ss")

4. @JsonSerialize

Used for attributes and getter () methods, which embed our custom code when serializing, such as when serializing a igedouble, after which 2 decimal places are restricted

5. @JsonDeserialize

This annotation is used on properties or setter methods to embed our custom code when deserializing

Code:

Entity class:

public class Student {
	private int id;
	private String name;
	private String password;
	@JsonSerialize (Using=mydateserializer.class)  //Serialization Converter
	@JsonDeserialize (Using=mydatedeserializer.class)  //Deserialization converter
	private date date;
	
	Public Student () {
		System.out.println ("Initialize Student object");
	}
Setter,getter omitted
}
Serialization Converter:

/**
 * Date Serialization Converter
 * @author root * * */Public
class Mydateserializer extends Jsonserializer<date >{

	@Override public
	void Serialize (date date, Jsongenerator Jgen, Serializerprovider provider)
			throws IOException, jsonprocessingexception {
		SimpleDateFormat sdf = new SimpleDateFormat ("Yyyy-mm-dd  HH:mm:ss");
		String str = sdf.format (date);
		Jgen.writestring (str);
	}
	
}
Date Deserialization converter:

/**
 * Date deserialization converter
 * @author root * * */Public
class Mydatedeserializer extends jsondeserializer< date>{

	@Override Public
	Date Deserialize (jsonparser parser, Deserializationcontext context)
			throws IOException, jsonprocessingexception {
		System.out.println ("deserialization");
		String datestr = parser.getvalueasstring ();
		SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd  HH:mm:ss");
		Date date = null;
		try {
			date = Sdf.parse (DATESTR),
		} catch (ParseException e) {
			//TODO auto-generated catch block
			e.pr Intstacktrace ();
		}
		return date;
	}
}





6. @JsonUnwrapped

When a member property in an entity class is an object of a class, the wrapper is ignored: (really bad explanation, see the example to understand)

User class:

public class User {
	private String name;
	private String password;
	@JsonIgnore
	private list<string> STRs;
	@JsonUnwrapped
	Private person p;
       Setter,getter omitted
}
Person class:

public class Person {  
    private String pName;  
    private int age;  
    Private Boolean sex; 
    @JsonFormat (pattern = "Yyyy-mm-dd hh-mm-ss")
    private Date birthday;  
    Private String word;  
    private double salary;  
Setter,getter omitted
  }


@Test public
	void testjsonunwrapped () throws ioexception{
		user U = New User ("Guofeipeng", "123");
		list<string> ls = new arraylist<string> ();
		Ls.add ("123");
		Ls.add ("234");
		Ls.add ("345");
		U.setstrs (LS);
		person person = new Person ("nomouse", +, True, new Date (), "Programmer",
				2500.0);
		U.SETP (person);
		Objectmapper mapper = new Objectmapper ();
		String json = mapper.writevalueasstring (u);  Java 2 JSON
		SYSTEM.OUT.PRINTLN (JSON);
		
		User user = Mapper.readvalue (JSON, User.class);//json 2 java
		System.out.println (user);
	
Note: The person attribute in the 1.User class is not @jsonunwarpped, and the converted JSON is: {"name": "Guofeipeng", "Password": "123", "P": {"age": +, "sex": true, " Birthday ":" 2014-12-22 07-15-29 "," word ":" Programmer "," pname ":" Nomouse "," Salary ":" 2500.00 "}}

2. Add the @jsonunwarpped annotation, then remove the P key (wrapper), the converted JSON is:

{"Name": "Guofeipeng", "Password": "123", "age": +, "sex": true, "Birthday": "2014-12-22 07-16-38", "word": "Programmer", "PName" : "Nomouse", "Salary": "2500.00"}


7. @JsonProperty

Acting on a field or method, used to serialize/deserialize a property, to avoid missing attributes, and to provide renaming of property names, such as in many scenarios where the properties of a Java object are written according to the specifications of the hump, but the actual display is similar to C-style or c++/microsolft Style

	@JsonProperty (value= "Stu_name")
	private String name;





/**
 * Date deserialization converter
 * @author root * * */Public
class Mydatedeserializer extends jsondeserializer< date>{

	@Override Public
	Date Deserialize (jsonparser parser, Deserializationcontext context)
			throws IOException, jsonprocessingexception {
		System.out.println ("deserialization");
		String datestr = parser.getvalueasstring ();
		SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd  HH:mm:ss");
		Date date = null;
		try {
			date = Sdf.parse (DATESTR),
		} catch (ParseException e) {
			//TODO auto-generated catch block
			e.pr Intstacktrace ();
		}
		return date;
	}
}


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.