I have a User class that I want to map to JSON using Jackson.
public class User {
private String name;
private int age;
prviate int securityCode;
If you don't want to put annotations on your Pojos you can also use Genson.
Here is how you can exclude a field with it without any annotations (you can also use annotations if you want, but you have the choice).
Genson genson = new Genson.Builder().exclude("securityCode", User.class).create();
// and then
String json = genson.serialize(user);
you also can gather all properties on an annotation class
@JsonIgnoreProperties( { "applications" })
public MyClass ...
String applications;
I had a similar case where I needed some property to be deserialized (JSON to Object) but not serialized (Object to JSON)
First i went for @JsonIgnore
- it did prevent serialization of unwanted property, but failed to de-serialize it too. Trying value
attribute didn't help either as it requires some condition.
Finally, working @JsonProperty
with access
attribute worked like a charm.
Field Level:
public class User {
private String name;
private int age;
@JsonIgnore
private int securityCode;
// getters and setters
}
Class Level:
@JsonIgnoreProperties(value = { "securityCode" })
public class User {
private String name;
private int age;
private int securityCode;
}
You have two options:
Jackson works on setters-getters of fields. So, you can just remove getter of field which you want to omit in JSON. ( If you don't need getter at other place.)
Or, you can use the @JsonIgnore
annotation of Jackson on getter method of that field and you see there in no such key-value pair in resulted JSON.
@JsonIgnore
public int getSecurityCode(){
return securityCode;
}
if you are using GSON you have to mark the field/member declarations as @Expose and use the GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
Don't forget to mark your sub classes with @Expose otherwise the fields won't show.