Skip to content

Instantly share code, notes, and snippets.

@sbglasius
Created November 23, 2018 09:04
Show Gist options
  • Save sbglasius/8b0a9cfe82d23f745c170dade525d340 to your computer and use it in GitHub Desktop.
Save sbglasius/8b0a9cfe82d23f745c170dade525d340 to your computer and use it in GitHub Desktop.
Attempt to serialize SpecData - not working
package tests
import com.fasterxml.jackson.annotation.JsonFilter
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.JsonMappingException
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonObjectFormatVisitor
import com.fasterxml.jackson.databind.node.ObjectNode
import com.fasterxml.jackson.databind.ser.FilterProvider
import com.fasterxml.jackson.databind.ser.PropertyFilter
import com.fasterxml.jackson.databind.ser.PropertyWriter
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider
import groovy.json.JsonBuilder
class SpecUtil {
static String toPrettyString(def data) {
new JsonBuilder(data).toPrettyString()
}
static String serialize(Object obj) {
ObjectMapper mapper = new ObjectMapper()
mapper.addMixIn(Object, DynamicMixIn)
FilterProvider filters = new SimpleFilterProvider()
.addFilter("dynamicFilter", new MyPropertyFilter())
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
return mapper.writer(filters).writeValueAsString(obj)
}
static toFile(Object obj) {
new File('tmp.obj').withObjectOutputStream {
it.writeObject(obj)
}
}
@JsonFilter("dynamicFilter")
static class DynamicMixIn {
}
static class MyPropertyFilter implements PropertyFilter {
boolean shouldSerialize(PropertyWriter writer) {
!(writer.name in ['metaclass', 'parent','specData','superSpec','subSpec','specsTopToBottom','specsBottomToTop','reflection','featureMethod','dataProviders'])
}
@Override
void serializeAsField(Object pojo, JsonGenerator gen, SerializerProvider prov, PropertyWriter writer) throws Exception {
if(shouldSerialize(writer)) {
writer.serializeAsField(pojo, gen, prov)
}
}
@Override
void serializeAsElement(Object elementValue, JsonGenerator gen, SerializerProvider prov, PropertyWriter writer) throws Exception {
if (shouldSerialize(writer)) {
writer.serializeAsElement(pojo, gen, prov)
}
}
@Override
void depositSchemaProperty(PropertyWriter writer, ObjectNode propertiesNode, SerializerProvider provider) throws JsonMappingException {
if (shouldSerialize(writer)) {
writer.depositSchemaProperty(propertiesNode, provider)
}
}
@Override
void depositSchemaProperty(PropertyWriter writer, JsonObjectFormatVisitor objectVisitor, SerializerProvider provider) throws JsonMappingException {
if (shouldSerialize(writer)) {
writer.depositSchemaProperty(objectVisitor, provider)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment