Reputation: 28804
I have one class say Person. When I use gson to convert it into json, sometimes I'd like to include the field name
, but sometimes I don't want to include it. Is there any api in gson that I can use for this kind of purpose ?
class Person {
int id;
String name;
}
Upvotes: 0
Views: 692
Reputation: 12215
The accepted answer is correct and the most flexible way to do it.
However depending on the case sometimes you can have benefit of annotation @Version
if it actually is a question about versioning different cases. So what you can do is make versions of your class like:
@Getter @Setter
public class User {
@Since(1.0)
private int id;
@Since(1.1)
private String name;
}
Then use GsonBuilder
to decide what version to handle, like:
Gson gson10 = getGsonBuilder().setVersion(1.0).create();
Gson gson11 = getGsonBuilder().setVersion(1.1).create();
Also
Upvotes: 1
Reputation: 4009
One way is to use ExclusionStrategy
in Gson
. It allows us to define a strategy to tell GsonBuilder
whether to serialize classes or fields with customized criteria.
Code snippet
I use a variable isNameIgnored
to enable/disable the field name
to be serialized dynamically.
boolean isNameIgnored = false;
ExclusionStrategy strategy = new ExclusionStrategy() {
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
@Override
public boolean shouldSkipField(FieldAttributes field) {
return isNameIgnored ? "name".equals(field.getName()) : false;
}
};
Then you can apply the strategy to GsonBuilder
for serialization as follows:
Gson gson = new GsonBuilder()
.addSerializationExclusionStrategy(strategy)
.create();
Upvotes: 2
Reputation: 1
look the api of gson,we can use the method 'toJson(java.lang.Object src, java.lang.Appendable writer)
' to specific genericized type of src
.
so, can we use diffrent type to enable/disable
the field?
Upvotes: 0