Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i format date or double values when persisting objects using simple xml

Tags:

java

android

I am using simple xml framework from http://simple.sourceforge.net/. How can i format the date or double values? I see a function called transform but how do I apply it all double and date fields in my class?

like image 771
bschandramohan Avatar asked Apr 07 '26 23:04

bschandramohan


2 Answers

There's two ways I can think of to do this.

First:

You can implement your own Matcher. You can pass this in to the Persister when you create it. Your Matcher only has to return a Transform for the types you are interested in. Any type your custom Matcher does not match is attempted by the default ones. You'll probably have to take a look at the source code and see how the DateTransform and FloatTransform are implemented. They are quite short so it's perfectly doable. This solution will be useful only if you want to transform all types in a specific way.

Second:

Create a String element that will hold the serialized data.

@Element(name = "myelement")
private String strMyElement;

private MyElementType myElement;

Then use the @Persist and @Validate annotations to hook into the serialization process.

@Persist
private void persist() {
  strMyElement = myElement.toString();
}

@Validate
private void validate() {
  myElement = myElement.fromString(strMyElement);
}

This way is a bit more of a hack but it's useful when you only need to override the default serialization in specific cases. It would probably get unwieldy if you had to do it for every instance of a specific type. In that case I'd use the first method.

like image 61
Rich Schuler Avatar answered Apr 10 '26 12:04

Rich Schuler


Simple uses a TransformCache to map types to Transformer objects. So if filed is of a java.lang.Date' type it will use theorg.simpleframework.xml.transform.DateTransform` to transform the Date object to String.

I guess you have to implement a custom Transformer for Date or the primitive long and (temporarily) replace the default Transformer for that type in the cache.

I didn't find any guide too, the drafted strategy is based on a look on the simple sources.

like image 24
Andreas Dolk Avatar answered Apr 10 '26 12:04

Andreas Dolk