Boon 简明教程

Boon - Generating Date

ObjectMapper 类可以用于处理 JSON 中不同的日期格式。它也可以用于生成日期对象。ObjectMapper 默认生成长毫秒版本的 Date。通过使用 JsonFactory.createUseJSONDates() 方法返回的 ObjectMapper,我们可以获取解析期间的字符串版本日期。

ObjectMapper class can be used to work with different date formats in JSON. It can be used to generate date object as well. By default ObjectMapper generates Date in long milliseconds version. Using ObjectMapper returned by JsonFactory.createUseJSONDates() method, we can get a string version of date during parsing.

Example

以下示例正在使用 ObjectMapper 类通过解析 JSON 生成 Date 字符串。

Following example is using ObjectMapper class to generate a Date string by parsing JSON.

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;
   }
}

Output

您将收到以下输出 −

You will receive the following output −

Tue Aug 11 17:01:00 IST 1998
{"name":"Mahesh","age":21,"dateOfBirth":"1998-08-11T11:31:00.034Z"}