Jakub Kubrynski
Jakub Kubrynski

Reputation: 14149

Change field name when serializing to JSON in Groovy

I'm using JsonOutput to serialize POGO into JSON. Is there any option to set name alternative for particular field?

class MyObject {
  def myField = "test" // in JSON I want to have myJsonField instead of myField
}

Upvotes: 2

Views: 3064

Answers (1)

dmahapatro
dmahapatro

Reputation: 50265

I guess you wont be able to transform the field name using JsonOutput, but you can easily use JsonBuilder to create your own transformation of name of the fields as shown below:

import groovy.json.*

class MyObject {
  def myField = "test"
  def otherField = "other"
}

def obj = new MyObject()
assert JsonOutput.toJson(obj) == /{"otherField":"other","myField":"test"}/

def builder = new JsonBuilder()
builder {
    obj.properties.each { prop ->
        if( !(prop.key in ['class', 'declaringClass', 'metaClass'] ) ) {
            ( prop.key == 'myField' ) ? 
                myJsonField( "$prop.value" ) : 
                    "$prop.key"( "$prop.value" )
        }
    }
}

assert builder.toString() == /{"otherField":"other","myJsonField":"test"}/

UPDATE
Or without JsonBuilder but JsonOutput:

def transform = { object ->
    object.properties.collectEntries{key, value ->
        !( key in ['class', 'declaringClass', 'metaClass'] ) ? 
            key == 'myField' ? 
                ['myJsonField', value] : [key, value] : 
                    [:]
    }
}
assert JsonOutput.toJson(transform(obj)) == 
                     /{"otherField":"other","myJsonField":"test"}/

Upvotes: 4

Related Questions