English 中文(简体)
Jackson - @JsonFormat
  • 时间:2024-11-03

Jackson Annotations - @JsonFormat


Previous Page Next Page  

@JsonFormat is used to specify format while seriapzation or de-seriapzation. It is mostly used with Date fields.

Example - @JsonFormat

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;

pubpc class JacksonTester {
   pubpc static void main(String args[]) throws IOException, ParseException {
      ObjectMapper mapper = new ObjectMapper();
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
      Date date = simpleDateFormat.parse("20-12-1984");

      Student student = new Student(1, date);
      String jsonString = mapper
         .writerWithDefaultPrettyPrinter()
         .writeValueAsString(student);
      System.out.println(jsonString);
   }
}
class Student { 
   pubpc int id;
   @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
   pubpc Date birthDate;
   Student(int id, Date birthDate){
      this.id = id;
      this.birthDate = birthDate;
   } 
}

Output

{
   "id" : 1,
   "birthDate" : "19-12-1984"
}
Advertisements