Skip to content

Instantly share code, notes, and snippets.

@mcquinne
Last active May 2, 2022 20:35
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcquinne/b115ab4cbdf4f1f5365de87f455e57a5 to your computer and use it in GitHub Desktop.
Save mcquinne/b115ab4cbdf4f1f5365de87f455e57a5 to your computer and use it in GitHub Desktop.
Spring Jackson JSON serializer for Groovy GStrings
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonProcessingException
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.ser.std.StdSerializer
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
@Component
class GStringJsonSerializer extends StdSerializer<GString> {
@Autowired
GStringJsonSerializer(ObjectMapper objectMapper) {
super(GString)
def module = new SimpleModule()
module.addSerializer(GString, this)
objectMapper.registerModule(module)
}
@Override
void serialize(GString value, JsonGenerator gen, SerializerProvider serializers)
throws IOException, JsonProcessingException {
gen.writeString(value.toString())
}
}
@mcquinne
Copy link
Author

mcquinne commented Sep 23, 2016

Drop this class into your Spring project to create a self-registering JsonSerializer bean which teaches Jackson to serialize Groovy GStrings. This way, if a RestController returns an object with a GString in it, it'll give you something rational like:

{
  "message": "Hello, world"
}

instead of the nonsense it would otherwise come up with:

{
  "message": {
    "strings": ["Hello, ", ""],
    "values": ["world"],
    "bytes":"SGVsbG8sIHdvcmxk",
    "valueCount":1
  }
}

Doing the same for XML serialization is left as an exercise for the reader, if you're into that sort of thing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment