I'm new to POJOs and am working on creating objects to represent JSON from Google APIs. How can I create a pojo for this JSON?
"notificationSettings": {
"notifications": [
{
"type": "eventCreation",
"method": "email"
},
{
"type": "eventChange",
"method": "email"
},
{
"type": "eventCancellation",
"method": "email"
},
{
"type": "eventResponse",
"method": "email"
}
]
}
I have the rest of the JSON figured out, however, the Gson.fromJSON() keeps returning null.
EDIT 1
This is what I have
private static class NotificationSettings{
public NotificationSettings(){
}
public NotificationSettings(Map<String, List<Notification>> notifications) {
super();
this.setNotifications(notifications);
}
public Map<String, List<Notification>> getNotifications() {
return notifications;
}
public void setNotifications(Map<String, List<Notification>> notifications) {
this.notifications = notifications;
}
private Map<String, List<Notification>> notifications;
}
private static class Notification{
public Notification(){
}
public Notification(String type, String method) {
super();
this.type = type;
this.method = method;
}
private String type;
private String method;
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(String type) {
this.type = type;
}
/**
* @return the method
*/
public String getMethod() {
return method;
}
/**
* @param method the method to set
*/
public void setMethod(String method) {
this.method = method;
}
}
EDIT 2 Another question, are the constructors with arguments required? In addition, is the toString() method required as well?
Thanks!
A POJO is a Plain Old Java Object, which is a class with fields and getters/setters. I don't think somebody that works with Java is new to POJOs unless it is learning Java. This is why I won't give the exact class structure, otherwise I would be doing your job.
You just need to define the type for the elements in your JSON string. Let's review the string and how can you map it:
"notificationSettings": { //name of class: NotificationSettings
"notifications": [ //array of Notification objects. It means you will need a Notification class as well
//and an array or List field called notification in NotificationSettings class
{ //this defines the structure for Notification class
"type": "eventCreation", //String field called type
"method": "email" //String field called method
},
{
"type": "eventChange",
"method": "email"
},
{
"type": "eventCancellation",
"method": "email"
},
{
"type": "eventResponse",
"method": "email"
}
]
}
From your implementation, looks like you should replace private Map<String, List<Notification>> notifications;
field to private List<Notification> notifications;
and make Notification
class a top class in its own file.