I have a basic SpringBoot 2.1.2.RELEASE app. Using Spring Initializer, JPA, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR with a restful architecture
I have this object that I return in a RestMethod:
public class MenuAlarm {
/**
*
*/
public MenuAlarm() {
super();
}
/**
*
*/
public MenuAlarm(Menu menu) {
this.menuAlias = menu.getName();
this.menuId = menu.getId();
menu
.getAlerts()
.forEach(a -> alarms.add(new Alarm(a)));
}
class Alarm {
public Alarm(MenuAlert menuAlert) {
this.percentage = menuAlert.getPercentage();
if (menuAlert.getCriteria() > 1) {
this.increase = true;
} else {
this.increase = false;
}
this.enabled = menuAlert.isEnabled();
}
public Alarm() {
super();
}
Integer percentage;
boolean increase;
boolean enabled;
}
String menuAlias;
Long menuId;
List<Alarm> alarms = new ArrayList<Alarm>();
public String getMenuAlias() {
return menuAlias;
}
public void setMenuAlias(String menuAlias) {
this.menuAlias = menuAlias;
}
public Long getMenuId() {
return MenuId;
}
public void setMenuId(Long menuId) {
this.menuId = menuId;
}
public List<Alarm> getAlarms() {
return alarms;
}
public void setAlarms(List<Alarm> alarms) {
this.alarms = alarms;
}
}
but when I return the result I got this error:
Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class com.tdk.api.json.MenuAlarm$Alarm and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.tdk.api.json.UserAlerts[“menuAlarms"]->java.util.ArrayList[0]->com.tdk.api.json.MenuAlarm["alarms"]->java.util.ArrayList[0])`
You haven't told Jackson how to serialize the inner Alarm class.
Jackson will attempt to serialize it as a bean (thus the reference to BeanSerializer), but you haven't provided any JavaBeans-compatible getter methods on Alarm.
Your options are to either to write a custom serializer for Alarm, or add some public getter methods like getPercentage.