A แจ็คสัน เป็นไลบรารีที่ใช้ Java และมีประโยชน์ในการแปลงออบเจ็กต์ Java เป็น JSON และ JSON เป็น Java Object เราสามารถจับคู่รูปแบบวันที่หลายรูปแบบในไลบรารี Jackson โดยใช้ @JsonFormat annotation เป็นคำอธิบายประกอบวัตถุประสงค์ทั่วไปที่ใช้สำหรับการกำหนดค่ารายละเอียดว่าค่าของคุณสมบัติจะถูกจัดลำดับอย่างไร @JsonFormat มีสามช่องสำคัญ:รูปร่าง รูปแบบ และเขตเวลา . รูปร่าง ฟิลด์สามารถกำหนดโครงสร้างเพื่อใช้สำหรับซีเรียลไลซ์เซชั่น (JsonFormat.Shape.NUMBER และ JsonFormat.Shape.STRING ) รูปแบบ ฟิลด์สามารถใช้ในการทำให้เป็นอันดับและดีซีเรียลไลซ์เซชัน สำหรับวันที่ รูปแบบประกอบด้วย SimpleDateFormat คำจำกัดความที่เข้ากันได้ และสุดท้าย เขตเวลา สามารถใช้ในการซีเรียลไลซ์เซชันได้ ค่าเริ่มต้นคือเขตเวลาเริ่มต้นของระบบ
ไวยากรณ์
@Target(value={ANNOTATION_TYPE,FIELD,METHOD,PARAMETER,TYPE})
@Retention(value=RUNTIME)
public @interface JsonFormat
ตัวอย่าง
import java.io.*;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonDateformatTest {
final static ObjectMapper mapper = new ObjectMapper();
public static void main(String[] args) throws Exception {
JacksonDateformatTest jacksonDateformat = new JacksonDateformatTest();
jacksonDateformat.dateformat();
}
public void dateformat() throws Exception {
String json = "{\"createDate\":\"1980-12-08\"," + "\"createDateGmt\":\"1980-12-08 3:00 PM GMT+1:00\"}";
Reader reader = new StringReader(json);
Employee employee = mapper.readValue(reader, Employee.class);
System.out.println(employee);
}
}
// Employee class
class Employee implements Serializable {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "IST")
private Date createDate;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm a z", timezone = "IST")
private Date createDateGmt;
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getCreateDateGmt() {
return createDateGmt;
}
public void setCreateDateGmt(Date createDateGmt) {
this.createDateGmt = createDateGmt;
}
@Override
public String toString() {
return "Employee [\ncreateDate=" + createDate + ", \ncreateDateGmt=" + createDateGmt + "\n]";
}
} ผลลัพธ์
Employee [ createDate=Mon Dec 08 00:00:00 IST 1980, createDateGmt=Mon Dec 08 07:30:00 IST 1980 ]