Context
In one of my team's internal tools, we use the Jackson library to serialize Java objects (Class A
) to JSON, so that we can eventually store the JSON in MongoDB.
We notice in the JSON file that there are these 2 extra variables _id
& _class
for the Java object Class A
.
The following is the Java definition of Class A
:
public class A {
@JsonIgnore
private int id;
// ... other variables
}
We're trying to find out where the _class
variable is getting inserted into the JSON file, because this variable is not defined in the Java class. So we suspected it might be the Jackson serializer.
The following is how Class A
is serialized. Java Class B
stores a list of Class A
. Class B
is the one getting serialized by the Jackson serializer. There is no implementation of a custom serializer for Class A
or B
.
Java definition of Class B
:
public class B {
List<A> dataList;
// ... other variables
}
How Class B
is getting serialized:
public class FileWriterService {
public void writeToFile(B objectB) {
ObjectMapper mapper = new ObjectMapper();
bw = new BufferedWriter(fr);
...
bw.write(mapper.writeValueAsString(objectB));
}
}
The sample JSON
output of Class A
is as follows:
{
"_id": ObjectId("..."),
"anotherVariableOfClassA": ...,
"_class": "com.companyName.internalTool.ClassA"
}
I don't see anywhere else in the code where Class A
is getting serialized. The Jackson serializer serializes Class B
directly.
Is there a way I can remove the _class
variable in the JSON file?
Reproducing the Code
public class A implements Serializable {
private static final long serialVersionUID = 1L;
@JsonIgnore
private int id;
private String tableName;
private String sql;
public A(int id, String tableName, String sql) {
this.id = id;
this.tableName = tableName;
this.sql = sql;
}
}
public class B {
private String name;
private List<A> data;
public B(String name, List<A> data) {
this.name = name;
this.data = data;
}
}
public class Driver {
public static void main(String[] args) {
// initializing A & B
A a = new A(1, "tableName", "SQL");
ArrayList<A> list = Arrays.asList(a);
B b = new B("name", list);
ObjectMapper mapper = new ObjectMapper();
String jsonOutput = mapper.writeValueAsString(b);
System.out.println(jsonOutput);
}
}