Groovy: Writing objects without Serializable
Problem Summary
You want to serialize an object to a file, but it doesn’t implement Serializable.
class User{
String name;
String phone;
String favoriteColor;
}
The Serializable interface is annoying. It’s a basic object. Just let me read/write the object!!
JSON Proposal
One solution is very straightforward - don’t use proper “Serialization” - because it may not actually be what you need. The downside to this is that ==
is not satisfied, but you probably do not need this!
Here’s a basic example using Groovy’s helpful JsonOutput and JsonSlurper classes.
def testUser = new User(
name: 'steven',
phone: '1-770-555-1212',
favoriteColor: 'red'
)
//convert to json
def testUserJson = JsonOutput.toJson(testUser)
//write to file
def outputFile = new File("testUser.json")
outputFile.write(testUserJson)
//read object from file
def testUser2 = JsonSlurper.parse(outputFile) as User
Cache implemenation using this approach
I added an implementation of the Grails Cache Plugin that uses this approach here: Grails Filesystem Cache Plugin
This had the added complexity of dynamic file names. Given arbitrary key types, and filename length limitations, I used SHA256(json(key)).json for the filename.