我正在使用JsonOutput将POGO序列化为JSON。是否有为特定字段设置名称替代的选项?
class MyObject {
def myField = "test" // in JSON I want to have myJsonField instead of myField
}
答案 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"}/
<强>更新强>
或者没有JsonBuilder
但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"}/