我對傑克遜有一個問題,我認爲應該很容易解決,但它會殺死我。傑克森json反序列化,json根元素
我有一個Java POJO類,它看起來像這樣(的getter和setter)
@JsonRootName(value = "notificacion")
public class NotificacionDTO extends AbstractDTO {
@JsonProperty(required=true)
private Integer instalacion;
@JsonProperty(required=true)
private Integer tipoNotificacion;
@JsonProperty(required=true)
private String mensaje;
}
這裏是AbstractDTO
public abstract class AbstractDTO implements Serializable {
public void validate() {
Field[] declaredFields = this.getClass().getDeclaredFields();
for (Field field : declaredFields) {
if (field.isAnnotationPresent(JsonProperty.class)){
if (field.getAnnotation(JsonProperty.class).required() && this.isNullParameter(field)) {
throw new RuntimeException(String.format("El parametro %s es null o no esta presente en el JSON.", field.getName()));
}
}
}
}
private boolean isNullParameter(Field field) {
try {
field.setAccessible(true);
Object value = field.get(this);
if (value == null) {
return true;
} else if (field.getType().isAssignableFrom(String.class)) {
return ((String) value).isEmpty();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return false;
}
}
我想反序列化JSON看起來像這樣成NotificacionDTO object:
{
"notificacion":
{
"instalacion":"1",
"tipoNotificacion":"2",
"mensaje":"Un Mensaje"
}
}
這是我的EndPoint
@Controller
@RequestMapping("/notificacion")
public class NotificacionEndPoint extends AbstractEndPoint{
@Autowired
private NotificacionService service;
@RequestMapping(value = {"", "/"}, method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void addNotification(@RequestBody NotificacionDTO notification) throws JsonParseException, JsonMappingException, IOException {
this.log.info("[POST RECEIVED] = " + notification);
notification.validate();
this.service.addNotification(notification);
}
}
我哈瓦這個
public class JsonObjectMapper extends ObjectMapper {
public JsonObjectMapper() {
super();
this.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
}
}
定製ObjectMapper當我文章中,我得到這個錯誤
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "notificacion" (class ar.com.tecnoaccion.services.notificacion.NotificacionDTO), not marked as ignorable (3 known properties: , "tipoNotificacion", "instalacion", "mensaje"])
at [Source: org.apache.catalina.connector[email protected]; line: 3, column: 5] (through reference chain: ar.com.tecnoaccion.services.notificacion.NotificacionDTO["notificacion"])
我嘗試把它添加到我的DTO
@JsonIgnoreProperties(ignoreUnknown = true)
但是當我驗證我的DTO的方法驗證所有的dto屬性是空的,我得到這個錯誤:
java.lang.RuntimeException: El parametro instalacion es null o no esta presente en el JSON.
我使用傑克遜2.2.3和3.2.1春季
謝謝你,對不起我的英語不好我來自阿根廷。
請翻譯了java.lang.RuntimeException:薩爾瓦多parametro instalacion上課空O否ESTA presente EN EL JSON。英文 – tom