ajax send json like
{
"id":"123123"
"parentId":"",
},
java class is:
public class Page{
private Long id;
private Long parentId;
}
as default, i get
{
"id":123123
"parentId":null
}
but i want parentId to be zero, what should i do ? thanks very much
CodePudding user response:
You should be able to initialise the default value, it will automatically assign that instead.
@JsonInclude(
value = JsonInclude.Include.NON_EMPTY,
content = JsonInclude.Include.NON_EMPTY)
public class Page {
private long id = 0;
private long parentId = 0;
}
CodePudding user response:
If initializing the attribute in the Page
class is not feasible or you also don't want to change the attribute from Long
to long
then you can implement a custom Jackson deserializer as follows:
public class CustomLongDeserializer extends JsonDeserializer<Long> {
@Override
public Long deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
String text = jp.getText();
if (text == null || text.isEmpty()) {
return 0;
} else {
return Long.valueOf(text);
}
}
}
Then you just need to configure its usage on the respective attribute:
public class Page{
private Long id;
@JsonDeserialize(using = CustomLongDeserializer.class)
private Long parentId;
}