this is a simple code that I'm using to create a JSON but i want it to ignore some fields just here. so i don't want to use @JsonIgnore annotation. but the problem is withoutAttribute doesn't work and all of the fields remain in JSON string. and i have another question. how can i format value of some fields with objectMapper. for example format the value of username field to **8t on changing to JSON without any annotation.
TestObject testObject = new TestObject("858t","444hg", "mina");
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter().withoutAttribute("username").withoutAttribute("password");
String s = ow.writeValueAsString(testObject);
System.out.println(s);
I expect output
{"name":"mina"}
but i get below result
{
"username" : "858t",
"password" : "444hg",
"name" : "mina"
}
this is the maven dependency that I'm using. i also tried other versions like 2.8.7
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
update: i used ExclusionStrategy of GSON library and it worked. but when i use it in server i have a wired heap space growth and just because of the bellow ExclusionStrategy used in my logger:
public class SecurityJsonExclusion implements ExclusionStrategy {
private Class<?> c;
ArrayList<String> fieldNames = new ArrayList<String>(Arrays.asList("username","password"));
public SecurityJsonExclusion(String... fieldNames) throws SecurityException {
if (fieldNames != null) {
Collections.addAll(this.fieldNames, fieldNames);
}
}
public SecurityJsonExclusion() {
}
public boolean shouldSkipClass(Class<?> arg0) {
return false;
}
public boolean shouldSkipField(FieldAttributes f) {
if (fieldNames == null || fieldNames.size() == 0) {
return false;
} else {
String name = f.getName();
for (String s : fieldNames) {
if (name.equalsIgnoreCase(s)) {
return true;
}
}
return false;
}
}
}
using it like this:
Gson gson = new GsonBuilder()
.setExclusionStrategies(new SecurityJsonExclusion()).setPrettyPrinting()
.create();
return gson.toJson(o);
even when i remove setExclusion part, gsonBuilder itself consumes a large amount of heap space.