Saturday, June 26, 2010

XStream - Json story (2)

Now I understand xstream much better after study their codes for maybe 20-30 hours. It is nice, but probably overkill for my purpose. Their documentation is good enough to get you going. But there are lots of more intricate that might be good to write.

One problems with XStream is that it is really designed for xml. For xml, it is fine to have something like


<birthday type="java.sql.Timestamp">
12-20-2004
<birthday>

It would be whole lots more complicated for json. Their solution (xstream 1.3.1, both jettison and there own driver) is

birthday:{
@class:java.sql.Timestamp,
$:12-20-2004
}

For my purpose, I only need the value, not the class information. I understand that it is useful information when you need to deserialize the json back into a java object. I have a object with type java.util.Date, with a value as java.sql.Timestamp, which is a subclass of java.util.Date. And xstream keeps spit out things like the above, while I only need a simple things like birthday:12-20-2004. When the object is really just a java.util.Date, and xstream generates the simple thing. These inconsistency completely messed up my code. I need a fairly complicated javascript code to handle the situation like such, while things are much easier to handle if xstream always convert it into the simple case. I tried all kinds of way to get around it but no luck. I looked into their engine, but it is quite complicated and I did not fully get it. And furthermore, their code (at least json driver) is under heavy development. I wa confused at first by very different code for the same class and finally realized that the eclipse show the jave source from maven repository (official 1.3.1 release) and I got the 1.3.1 developing trunk. Man, they are very different and it seems they are trying something quite different. Back to the topic,
I tried to register the the Date converter for java.sql.Timestamp.class and it does not work. Finally I found the way to work:

xstream.addDefaultImplementation(Date.class,java.sql.Timestamp.class);

Frankly, I do not quite get why it works. And this add some discomforting.

Another not-so-nice thing about xstream is that it does the reflection on fields only, not the common bean convention. So some fake beans does not get converted. I wrote a couple of converter for complex classes I have. And that is much easier to write it than to looking through all the source and documentation.

But the final problem comes with the multiple models. XStream can only do one at a time. So I give up and goes to the original approach and as I explain in the last post, things work out pretty well.

No comments :