Introduction: In Web application development, it is often necessary to convert objects into JSON strings, there will be default output content does not meet the requirements of the situation, such as DateTime. Custom serializer can typically be used to customize the JSON character output.
1. Set the custom serializer in the GetXXX method in the object
public class MyObject { private DateTime startdate; @JsonSerialize (using = datetimejsonserializer.class) public DateTime getstartdate () { return this.startdate; }}
Description
1. @JsonSerializer defines a custom serial number class,
2. Using the custom Java conversion class specified
2. Implement a custom serializer
public class Datetimejsonserializer extends jsonserializer<datetime> {private static DateTimeFormatter formatter = Datetimeformat.forpattern ("Yyyy-mm-dd hh-mm-ss"); @Overridepublic void Serialize (DateTime value, Jsongenerator generator,serializerprovider arg2) throws IOException, jsonprocessingexception {generator.writestring (Formatter.print (value));}}
In this example, the conversion of JSON output type information is primarily for DateTime.
DateTime is entered as a generic class t when declaring a type, and in a specific method, it is passed as value. Generator.writestring () to output the JSON string information.
3. Conduct the test
Before you do a custom formatted output
After you have formatted the output:
4. Summary
With @jsonserialize this artifact, you can output JSON result information as you wish.
Reference documents
1. Http://stackoverflow.com/questions/3269459/how-to-serialize-joda-datetime-with-jackson-json-processer
2. Http://stackoverflow.com/questions/14026081/jackson-automatic-formatting-of-joda-datetime-to-iso-8601-format
How to customize JSON output for a specific field in an object