I have written code to serialize objects to JSON and BSON. According to my output, the BSON produced is greater in size than the JSON. Is this expected?
From my code for Bson.class
(using Jackson and bson4jackson)
private ByteArrayOutputStream baos = new ByteArrayOutputStream();
private BsonFactory fac = new BsonFactory();
private ObjectMapper mapper = new ObjectMapper(fac);
public Bson(Object obj) throws JsonGenerationException,
JsonMappingException, IOException {
mapper.writeValue(baos, obj);
}
public int size() {
return baos.size();
}
public String toString() {
byte[] bytes = baos.toByteArray();
return new String(bytes);
}
From my Json.class
private ByteArrayOutputStream baos = new ByteArrayOutputStream();
private ObjectMapper mapper = new ObjectMapper();
public Json(Object obj) throws JsonGenerationException,
JsonMappingException, IOException {
mapper.writeValue(baos, obj);
}
(size()
and toString()
as above)
My POJOs are Person.class
and Address.class
.
In my main class:
Address a = new Address("Jln Koli", "90121", "Vila", "Belgium");
Person p = new Person("Ali Bin Baba", new Date(), 90.0, 12, a);
List<Person> persons = new LinkedList<>();
persons.add(p);
persons.add(p);
Bson bson = new Bson(persons);
Json json = new Json(persons);
System.out.println("Bson : " + bson.size() + ", data : " + bson.toString());
System.out.println("Json : " + json.size() + ", data : " + json.toString());
The ouput:
Bson : 301, data : -
Json : 285, data : [{"name":"Ali Bin Baba","birthd...
My Question:
- Is that output true, or is my code wrong?
- Any suggestion to check/test, to compare the sizes of BSON and JSON?