在Groovy中序列化为JSON时更改字段名称

时间:2014-01-25 18:25:56

标签: json groovy

我正在使用JsonOutput将POGO序列化为JSON。是否有为特定字段设置名称替代的选项?

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

1 个答案:

答案 0 :(得分:4)

我猜您无法使用JsonOutput转换字段名称,但您可以轻松使用JsonBuilder创建自己的字段名称转换,如下所示:

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"}/

<强>更新
或者没有JsonBuilderJsonOutput

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"}/