【问题标题】:How return a empty JSON in Spring MVC?如何在 Spring MVC 中返回一个空的 JSON?
【发布时间】:2019-06-08 02:52:11
【问题描述】:

我正在使用带有 GET 方法的 ajax,我正在等待接收 JSON,但有时响应为 null 并得到错误:

SyntaxError: JSON 输入意外结束

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)
            }
        });

    })
});

在控制器中:

@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?        
}

【问题讨论】:

    标签: ajax spring-mvc


    【解决方案1】:

    有几种方法可以做到这一点。首先是配置用于序列化 JSON 的 JSON 库。如果是 Jackson ,您可以使用 @JsonInclude 排除所有不序列化的空属性,并返回一个空的 MntPaciente

    @JsonInclude(Include.NON_EMPTY)
    public class MntPaciente {
    
    }
    
    public @ResponseBody MntPaciente buscarPaciente(@RequestParam("expediente") String expediente) {
    
        ....
        return new MntPaciente();  
    }
    

    要全局应用而不是为每个对象配置,您可以使用

    ObjectMapper om = new ObjectMapper();
    om.setSerializationInclusion(Include.NON_EMPTY);
    

    另一种方法是把控制器方法改成返回ResponseEntity,直接返回一个空的JSON字符串:

    public @ResponseBody ResponseEntity buscarPaciente(@RequestParam("expediente") String expediente) {
    
          if (mntPaciente!= null) {
             return ResponseEntity.of(mntPaciente);       
          }else{
             return ResponseEntity.of("{}");
           }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多