Tomee 7.0.2, JSON date serialization, and workaround

When @Produces({ MediaType.APPLICATION_JSON }) and @XmlRootElement are put on a service and model classes respectively, Tomee serializes an entity to JSON automatically.

However, when java.util.Date is serialized, then the result was very strange, I expected this

"2012-01-02T11:12+07"

but what I actually got from Tomee 7.0.2 was

"25550102111200+0700"

So I tested with Tomee 1.7.4 instead of 7.0.2; and it works. Apache web site mentioned that Johnzon is used in Tomee 7.0.2, so I thought maybe the problem is there. I added a customized JohnzonConverter as follow:

In model:

@XmlRootElement
@Entity
public class Word {
...
    @JohnzonConverter(MyDateConverter.class)
    @Temporal(TemporalType.TIMESTAMP)
    private Date t1;
 ...
}

MyDateConverter.java:

import org.apache.johnzon.mapper.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import static java.util.Locale.ENGLISH;

public class MyDateConverter implements Converter<Date> {

    @Override
    public String toString(Date date) {
        return new SimpleDateFormat("yyyy-MM-dd'T'HH:mmX", ENGLISH).format(date);
    }

    @Override
    public Date fromString(String s) {
        try {
            return new SimpleDateFormat("yyyy-MM-dd'T'HH:mmX", ENGLISH).parse(s);
        } catch (ParseException e) {
            throw new IllegalArgumentException(e);
        }
    }
}

Then even Tomee 7.0.2 works in the way I expected.

P.S. I added this to pom.xml too

<dependency>
  <groupId>org.apache.johnzon</groupId>
  <artifactId>johnzon-mapper</artifactId>
  <version>1.0.0</version>
  <scope>provided</scope>
</dependency>

 

Advertisements

ใส่ความเห็น

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / เปลี่ยนแปลง )

Twitter picture

You are commenting using your Twitter account. Log Out / เปลี่ยนแปลง )

Facebook photo

You are commenting using your Facebook account. Log Out / เปลี่ยนแปลง )

Google+ photo

You are commenting using your Google+ account. Log Out / เปลี่ยนแปลง )

Connecting to %s