POJO
POJO is short for Plain Old Java Object; it's a cute way of referring to simple classes like Course
that are free of any special restriction or requirement that might be imposed by using a third-part library or a framework. The term was coined by Martin Fowler, Rebecca Parsons and Josh MacKenzie. In their own words: "we wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it's caught on very nicely."
Gson helps us to directly convert a POGO to JSON and read it back; it literally takes one statement to do so and as such it helps to reduce the amount of code you have to write:
Course course = new Course("EN.500.112","GATEWAY COMPUTING: JAVA");
Gson gson = new Gson();
System.out.println(gson.toJson(course));
The code snippet above will print the following output:
{
"offeringName": "EN.500.112",
"title": "GATEWAY COMPUTING: JAVA"
}
Notice for each JSON property, the property name is a class attribute (e.g. offeringName
) and the property value is the value of that attribute (e.g. EN.500.112
).
Imagine we wanted to instead print out the following
{
"Offering Name": "EN.500.112",
"Title": "GATEWAY COMPUTING: JAVA"
}
Notice the capitalization of the first letter of property names and the space between "Offering" and "Name". We cannot create a class field in Java as Offering Name
; it would not be a valid identifier. But Gson allows us to annotate fields (using @SerializedName
annotation) to generate this desired output:
import com.google.gson.annotations.SerializedName;
import java.util.Objects;
/**
* Represent a Course.
*/
public class Course {
@SerializedName(value = "Offering Name")
private final String offeringName;
@SerializedName(value = "Title")
private final String title;
// the rest of the class remains the same!
}
If you now run the code snippet above, you will get the following output:
{
"Offering Name": "EN.500.112",
"Title": "GATEWAY COMPUTING: JAVA"
}
You can also use Gson annotations to ignore certain class attributes, etc. Gson can do a lot! Consult its "User Guide".