CodexBloom - Programming Q&A Platform

Handling XML Deserialization with Custom Date Format in Jackson - Java 11 guide

👀 Views: 334 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-03
jackson xml deserialization java-11 Java

I'm learning this framework and I'm working with an scenario with deserializing an XML response that contains a date formatted in a non-standard way using Jackson in my Java 11 application... The XML looks like this: ```xml <order> <id>12345</id> <date>2023-02-15T14:30:00Z</date> </order> ``` I have a corresponding Java class defined as follows: ```java import com.fasterxml.jackson.dataformat.xml.XmlMapper; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; public class Order { private String id; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'") private Date date; // Getters and Setters } ``` When I attempt to deserialize the XML using the following code: ```java XmlMapper xmlMapper = new XmlMapper(); Order order = xmlMapper.readValue(xmlString, Order.class); ``` I receive the following behavior: ``` com.fasterxml.jackson.databind.exc.InvalidFormatException: want to parse "2023-02-15T14:30:00Z": not a valid representation (behavior: "Text '2023-02-15T14:30:00Z' could not be parsed: "Invalid format: "2023-02-15T14:30:00Z"") ``` I've tried adjusting the date format pattern in the `@JsonFormat` annotation to match various potential formats, but nothing seems to work. I even checked the XML input string for extra whitespace or characters, and everything seems fine. Is there something specific to the `XmlMapper` that requires a different approach to handle this scenario? Any suggestions on how to correctly configure Jackson to parse this date format would be greatly appreciated. Has anyone else encountered this? This is my first time working with Java 3.9. Any pointers in the right direction? How would you solve this?