gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:20:09 24 4
gpt4 key购买 nike

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

最佳答案

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

class Dummy {   

String f1
private String f2

}

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

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

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

关于json - 排除使用 Groovy JsonOutput 序列化的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44909522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com