Reputation: 172
I'm using ajax with GET method, I'm waiting receive a JSON but sometime the response is null and get the error:
SyntaxError: Unexpected end of JSON input
ajax:
$(document).ready(function() {
$("#form_data").submit(function(e) {
e.preventDefault()
var expediente = $('#expediente').val();
$.ajax({
url : 'buscarPaciente' + '?expediente=' + expediente,
dataType : "json",
type : "GET",
contentType : 'application/json',
mimeType : 'application/json',
success : function(data) {
console.log(data.nombre);
},
error : function(xhr, status, error) {
console.log(error)
}
});
})
});
in the controller:
@RequestMapping(value="/buscarPaciente", method = RequestMethod.GET)
public @ResponseBody MntPaciente
buscarPaciente(@RequestParam("expediente") String expediente) {
MntPaciente mntPaciente = servicePx.findByexpediente(expediente);
if (mntPaciente!= null) {
return mntPaciente;
}
return null; // Should I return an empty json? how?
}
Upvotes: 0
Views: 3206
Reputation: 90507
There are several ways to do it. The first is to configure the JSON library that used to serialise JSON .In case of Jackson
, you can use @JsonInclude
to exclude all the empty properties not to serialise and just return an empty MntPaciente
:
@JsonInclude(Include.NON_EMPTY)
public class MntPaciente {
}
public @ResponseBody MntPaciente buscarPaciente(@RequestParam("expediente") String expediente) {
....
return new MntPaciente();
}
To apply globally rather to configure for each object , you could use
ObjectMapper om = new ObjectMapper();
om.setSerializationInclusion(Include.NON_EMPTY);
The other way is to change the controller method to return ResponseEntity
and directly return a empty JSON string :
public @ResponseBody ResponseEntity buscarPaciente(@RequestParam("expediente") String expediente) {
if (mntPaciente!= null) {
return ResponseEntity.of(mntPaciente);
}else{
return ResponseEntity.of("{}");
}
}
Upvotes: 1