serialization - Serializing Joda DateTime using groovy.json -
i have simple pojo class fueling want serialize json using built in groovy json library. application halts when trying serialize.
class fueling { int id; int mileage; double amount; double cost; datetime datetime; string userid;
}
the following tests renders java.lang.stackoverflowerror:
@test void parsejoda(){ def fueling = new fueling(amount: 1.0, cost: 2.3, mileage: 123, datetime: datetime.now(datetimezone.utc)); def jsonf = jsonoutput.tojson(fueling); }
how can make serialization work?
edit: json data persisting , not display purpuses, actual serialization result format not important long able deserialized again
given don't care format, 1 simple workaround use maps groovy json api input/output , add in little code translate domain objects , maps.
serializing
you can use map returned getproperties
as-is 2 modifications: converting datetime
instance it's long
millisecond representation , removing class
entry (which lead memory errors me)
def serialize(){ def fueling = new fueling(amount: 1.0, cost: 2.3, mileage: 123, datetime: datetime.now(datetimezone.utc)); jsonoutput.tojson( fueling.properties.collectentries { k, v -> [(k): k == 'datetime' ? v.millis : v] // represent datetime milliseconds }.findall { it.key != 'class' // remove unnecessary 'class' property } ) }
deserializing
you can pass map jsonslurper spits out directly fueling
constructor slight modification of converting datetime
entry long
datetime
instance
def deserialize() { string json = '{"userid":null,"cost":2.3,"id":0,"datetime":1439839235603,"amount":1.0,"mileage":123}' map props = new jsonslurper().parsetext(json) new fueling(props.collectentries { k, v -> [(k): k == 'datetime' ? new datetime(v) : v ] // convert datetime }) }
of course, there comes point when domain object tree large/complex enough warrant use of more extensible 3rd-party json library.
Comments
Post a Comment