Last active
February 11, 2025 19:18
-
-
Save mcquinne/b115ab4cbdf4f1f5365de87f455e57a5 to your computer and use it in GitHub Desktop.
Spring Jackson JSON serializer for Groovy GStrings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
instead of the nonsense it would otherwise come up with:
Doing the same for XML serialization is left as an exercise for the reader, if you're into that sort of thing.