排除使用Groovy JsonOutput序列化的字段

问题描述 投票:2回答:3

如何在groovy中使用JsonOutput.toJson(..)时排除特定字段的序列化?

鉴于课程:

class Dummy {
  String f1
  transient String f2
}

码:

// synthetic getter and setter should be preserved
Dummy dummy = new Dummy(f1: "hello", f2: "world")
String json = JsonOutput. toJson(dummy )
println json

将导致:

{"f1":"hello", "f2":"world"}

应该导致:

{"f1":"hello"}
json serialization groovy
3个回答
1
投票

您还可以将f2属性显式设为私有

class Dummy {   

String f1   
private String f2

}

更新:我不相信有一种“明确”的做法 - 如果我错了,请纠正我。我能想到的唯一解决方案是定义一个带有不寻常命名的getter方法,例如:

class Dummy {     
String f1    
private String f2
def f2Value() { return f2 }
}

这样可以访问字段值,但JsonOutput会忽略它。


0
投票

根据Groovy的定义获取所有属性。你可以。 G。让吸气剂无法操作

class Dummy {
  String f1
  String f2
  def getF2() {
    throw new RuntimeException()
  }
}

groovy.json.JsonOutput.toJson(new Dummy(f1: "hello", f2: "world"))

这将返回{"f1":"hello"}


0
投票

如果您使用groovy> = 2.5.0,您可以使用JsonGenerator.Options排除字段:

class Dummy {
    String f1
    String f2
}
def dummy = new Dummy(f1: "hello", f2: "world")
def generator = new groovy.json.JsonGenerator.Options()
    .excludeFieldsByName('f2')
    .build()
assert generator.toJson(dummy)=='{"f1":"hello"}'

希望能帮助到你。

© www.soinside.com 2019 - 2024. All rights reserved.