Reputation: 10549
How to exclude specific fields from being serialized when using the JsonOutput.toJson(..)
in groovy?
Given class:
class Dummy {
String f1
transient String f2
}
Code:
// synthetic getter and setter should be preserved
Dummy dummy = new Dummy(f1: "hello", f2: "world")
String json = JsonOutput. toJson(dummy )
println json
Will result in:
{"f1":"hello", "f2":"world"}
Should result in:
{"f1":"hello"}
Upvotes: 3
Views: 2353
Reputation: 1195
if you're using groovy >= 2.5.0 you could use JsonGenerator.Options
to exclude fields:
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"}'
Hope it helps.
Upvotes: 3
Reputation: 406
You can also make the f2 property explicitly private
class Dummy {
String f1
private String f2
}
Update: I don't believe there is a "clear" way of doing this - correct me if I'm wrong. The only solution I can think of is defining a getter method with an unusual naming, ex:
class Dummy {
String f1
private String f2
def f2Value() { return f2 }
}
This way the field value would be accessible, but will be ignored by JsonOutput.
Upvotes: 1
Reputation: 38724
All properties as per the definition of Groovy are taken. You could e. g. make the getter inoperable like
class Dummy {
String f1
String f2
def getF2() {
throw new RuntimeException()
}
}
groovy.json.JsonOutput.toJson(new Dummy(f1: "hello", f2: "world"))
which will return {"f1":"hello"}
Upvotes: 0