对象映射程序无法序列化Object类的引用



我有一个通知类:

package com.code2hack.notification;
public class Notification {
private Object message;
private NotificationType type;
public static Notification create(NotificationType type,Object message){
return new Notification(message,type);
}
public Notification(){
}
public Notification(Object message,NotificationType type){
this.message = message;
this.type = type;
}
@Override
public String toString() {
return "Notification{" +
"message=" + message +
", type=" + type +
'}';
}
public <T> T getMessage(Class<T> type){
return (T)this.message;
}
public NotificationType getType(){
return this.type;
}
public void setType(NotificationType type){
this.type = type;
}
public void setMessage(Object message){
this.message = message;
}
}

当我使用spring中的ObjectMapper时,它不会将消息字段转换为Json。

public static void main(String ...str){
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(Notification.create(NotificationType.NEW_SCHEDULE,"NEW Schedule"));
System.out.println(json);
}

这不是将Notification中的消息属性转换为json。

我能做什么吗?

因为您在类中没有使用getters,所以jackson不会打印它,除非您向他指定message是json的一部分。

@JsonProperty
private Object message;

这应该做的工作

相关内容

最新更新