How to customize JSON output for a specific field in an object

Source: Internet
Author: User

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

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.