📅  最后修改于: 2020-11-18 09:07:17             🧑  作者: Mango
ObjectMapper类可用于在JSON中使用不同的日期格式。它也可以用于生成日期对象。默认情况下,ObjectMapper会生成长毫秒版本的Date。使用JsonFactory.createUseJSONDates()方法返回的ObjectMapper,我们可以在解析期间获取日期的字符串版本。
下面的示例使用ObjectMapper类通过解析JSON来生成Date字符串。
import java.util.Date;
import org.boon.json.JsonFactory;
import org.boon.json.ObjectMapper;
public class BoonTester {
public static void main(String args[]) {
ObjectMapper mapper = JsonFactory.createUseJSONDates();
String jsonString = "{\"name\":\"Mahesh\", \"age\":21, \"dateOfBirth\":\"1998-08-11T11:31:00.034Z\" }";
//mapper converts String to date automatically
Student student = mapper.readValue(jsonString, Student.class);
System.out.println(student.dateOfBirth);
//Mapper converts date to date string now
jsonString = mapper.writeValueAsString(student);
System.out.println(jsonString);
}
}
class Student {
public String name;
public int age;
public Date dateOfBirth;
public Student(String name, int age, Date dateOfBirth) {
this.name = name;
this.age = age;
this.dateOfBirth = dateOfBirth;
}
}
Tue Aug 11 17:01:00 IST 1998
{"name":"Mahesh","age":21,"dateOfBirth":"1998-08-11T11:31:00.034Z"}