我是POJO的新手,正致力于创建从Google API中表示JSON的对象。 如何为这个JSON创建一个pojo?
"notificationSettings": {
"notifications": [
{
"type": "eventCreation",
"method": "email"
},
{
"type": "eventChange",
"method": "email"
},
{
"type": "eventCancellation",
"method": "email"
},
{
"type": "eventResponse",
"method": "email"
}
]
}
我已经找到了JSON的其余部分,但是,Gson.fromJSON()一直返回null。
编辑1
这就是我所拥有的
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;
}
}
编辑2 另一个问题是需要参数的构造函数吗?另外,是否还需要toString()方法?
谢谢!
答案 0 :(得分:0)
POJO是一个普通的旧Java对象,它是一个包含字段和getter / setter的类。我不认为使用Java的人对POJO来说是新手,除非它正在学习Java。这就是为什么我不会给出确切的班级结构,否则我会做你的工作。
您只需要为JSON字符串中的元素定义类型。让我们回顾一下这个字符串,你如何映射它:
"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"
}
]
}
从您的实施中,您应该将private Map<String, List<Notification>> notifications;
字段替换为private List<Notification> notifications;
,并使Notification
类成为其自己文件中的顶级类。