JAXB Custom Binding – Java.util.Date / Spring 3 Serialization
Join the DZone community and get the full member experience.
Join For Freejaxb can handle java.util.date serialization, but it expects the following format: “yyyy-mm-ddthh:mm:ss “. what if you need to format the date object in another format?
i had the same issue when i was working with spring mvc 3 and jackson json processor , and recently, i faced the same issue working with spring mvc 3 and jaxb for xml serialization .
let’s dig into the issue:
problem:
i have the following java beans which i want to serialize in xml using spring mvc 3:
and i have another object which is going to wrap the pojo above:
in my spring controller, i’m going to return a list of company through the the @responsebody annotation – which is going to serialize the object automatically with jaxb:
when i call the controller method, this is what it returns to the view:
note the date format. it is not the format i expect it to return. i need to serialize the date in the following format: “ mm-dd-yyyy “
solution:
i need to create a class extending the xmladapter and override the marshal and unmarshal methods and in these methods i am going to format the date as i need to:
package com.loiane.util;
import java.text.simpledateformat;
import java.util.date;
import javax.xml.bind.annotation.adapters.xmladapter;
public class jaxbdateserializer extends xmladapter<string, date>{
private simpledateformat dateformat = new simpledateformat("mm-dd-yyyy");
@override
public string marshal(date date) throws exception {
return dateformat.format(date);
}
@override
public date unmarshal(string date) throws exception {
return dateformat.parse(date);
}
}
and in my java bean class, i simply need to add the @xmljavatypeadapter annotation in the get method of the date property.
if we try to call the controller method again, it is going to return the following xml:
problem solved!
happy coding!
from http://loianegroner.com/2011/06/jaxb-custom-binding-java-util-date-spring-3-serialization/
Opinions expressed by DZone contributors are their own.
Trending
-
Rule-Based Prompts: How To Streamline Error Handling and Boost Team Efficiency With ChatGPT
-
An Overview of Cloud Cryptography
-
Grow Your Skills With Low-Code Automation Tools
-
The Role of Automation in Streamlining DevOps Processes
Comments