📅  最后修改于: 2023-12-03 15:32:43.997000             🧑  作者: Mango
Java 8 introduced a new date-time API that provides better support for handling date and time. One of the classes in this API is the LocalDateTime class that represents a date-time object without a time-zone.
JSON is a widely used standard for data interchange between client and server over the web. In Java programming, converting Java objects to JSON and vice versa is a common requirement.
The Java 8 date-time API provides a built-in way to convert LocalDateTime objects to JSON format using the com.fasterxml.jackson.databind.ObjectMapper
class.
Here's an example of how to convert a LocalDateTime object to JSON using ObjectMapper:
import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.LocalDateTime;
public class LocalDateTimeJSONExample {
public static void main(String[] args) throws Exception {
LocalDateTime dateTime = LocalDateTime.now();
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(dateTime);
System.out.println("JSON representation of LocalDateTime object: " + json);
}
}
Output:
JSON representation of LocalDateTime object: "2021-12-22T20:32:52.998618"
The above code snippet first creates a LocalDateTime object using the now()
method which returns the current date-time. Then an instance of the ObjectMapper class is created and used to convert the LocalDateTime object to JSON format using the writeValueAsString()
method. Finally, the JSON representation of the LocalDateTime object is printed to the console.
Conversely, you can convert JSON string to a LocalDateTime object using the readValue()
method as shown in the following code snippet:
String json = "\"2021-12-22T20:32:52.998618\"";
ObjectMapper objectMapper = new ObjectMapper();
LocalDateTime dateTime = objectMapper.readValue(json, LocalDateTime.class);
System.out.println("LocalDateTime object from JSON: " + dateTime);
Output:
LocalDateTime object from JSON: 2021-12-22T20:32:52.998618
The above code first creates a JSON String and then creates an ObjectMapper instance to convert the JSON string back to a LocalDateTime object using the readValue()
method. Finally, the LocalDateTime object is printed to the console.
In conclusion, the Java 8 date-time API provides an easy and convenient way to convert LocalDateTime objects to JSON and vice versa using the Jackson Object Mapper class.