Serializing and deserializing POJOs in to many formats using Apache Juneau

Shalitha Suranga
Nov 12, 2018 · 3 min read
Apache Juneau logo

POJO (Plain Old Java Objects) are normal reusable java objects with several rules like,

  • Having getters and setters per each private property
  • Only inherits methods from default Object class

POJOs can be serialized/deserialized easily by implementing Serializable interface from java API. But how about serializing in to another formats like JSON, XML or HTML. This is where we can use a sub module of Apache Juneau

Apache Juneau

Getting Started with juneau-marshall

  • JSON
  • XML
  • HTML
  • UON (URL-Encoded Object Notation)
  • URL-Encoding
  • MessagePack
  • SOAP/XML
  • CSV

Download jar or simply add maven dependency to start with a marshaling example

<dependency>
  <groupId>org.apache.juneau</groupId>
  <artifactId>juneau-marshall</artifactId>
  <version>7.2.1</version>
</dependency>

Create a simple POJO class Person.java as per below

Person.java

Here @BeanConstructor annotation is required for parsing back to objects and it is optional for serialization.

Serialization

This will output human readable JSON of serialized pojo object.

{
  "name": "Jackson",
  "age": 24,
  "nickNames": ["Jil","Bil","Rock"],
  "city": "Colombo"
}

If you want in XML simply use XmlSerializer class

Also can serialized to HTML too..

HTML serialized instance of Person

Serializers use builder pattern so you will be able to easily customize those as you wish by using chain methods eg — if you need single quotes instead double quotes for JSON use builder as JsonSerializer.create().sq().build();

Juneau supports many formats for serialization. See all supported serializers here

Deserialization

This will simply output string representation of nickNames array.

june-marshall does the parsing and serializing recursively. Therefore aggregated beans also will work properly. For somewhat complex example for serialization see this

Conclusion

Apache Juneau is open source and anyone can contribute to improve the project by adding new features or resolving issues from issue tracker. It is currently in used by companies such as IBM, The Open Group, and Salesforce. Begin by cloning the repository today! 👍

See community for contribution guide

See you in next article. I am planning to write more about Apache Juneau.

Cheers!!

References

Shalitha Suranga

Written by

Software Engineer at 99xt | Apache Committer