首页 文章

Spring @ResponseBody JSON

提问于
浏览
0

我有一个Spring 3控制器,它返回一个JSON对象 . 我正在使用@ResponseBody注释和jackson-mapper-asl jar,Spring将自动处理JSON转换 . 3个return语句返回不同的JSON格式 . 可以通过使用Object修改getPersonDetails方法的返回类型来处理这个问题,还是有更好的方法 .

@RequestMapping(value="/test", method=RequestMethod.GET)
public @ResponseBody List<Person> getPersonDetails() {


    List<Person> listPerson = null;
    try {
        // Call to service and get the list of Person
        listPerson = getPersonList();
        if(CollectionUtils.isNotEmpty(listPerson)) {
            // Return JSON object
            //{"Name":"XYZ", "Age":25}
        } else {
            // Return JSON object
            //{"InformationMessage":"No data found."}
        }
    } catch(final Exception e) {
        // Return JSON object
        // {"ExceptionMessage":"Exception in controller."}
    }
}

5 回答

  • 0

    我会用 ResponseEntity<?>

    @RequestMapping(value="/test", method=RequestMethod.GET)
    public @ResponseBody ResponseEntity<List<Person>> getPersonDetails() {
    
    
        List<Person> listPerson = null;
        try {
            // Call to service and get the list of Person
            listPerson = getPersonList();
            if(CollectionUtils.isNotEmpty(listPerson)) {
                return new ResponseEntity<>(listPerson, HttpStatus.OK);
            } else {
                return new ResponseEntity(HttpStatus.NOT_FOUND);
            }
        } catch(final Exception e) {
             return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
  • 0

    你可以这样的事情

    @RequestMapping(value="/test", method=RequestMethod.GET)
    public @ResponseBody ResponseEntity<List<Person>> getPersonDetails() {
    try{
    if(dataAvailable) // if success 
    { 
    
    return new ResponseEntity<List<Person>>(yourlist, responseHeaders, HttpStatus.OK);
    }
    else{
    return new ResponseEntity<List<Person>>(HttpStatus.NOT_FOUND);
    }
    
    }catch(Exception e){
    // your custom exception here
    throw new PersonNotFoundException();
    }
    
    }
    

    注意:这里没有在IDE中输入,任何语法错误都可以随意编辑 .

  • 1

    此外:没有必要通过“消息对象”来表明出现了问题 . 这就是HTTP状态代码的用途 .

    我会去注入HttpServletResponse并使用 setStatus() 来指示错误,表示 404500 . 此外,您可以使用 getWriter().write("{\"ExceptionMessage\":\"Exception in controller.\"}") 向身体发送消息

    @RequestMapping(value="/test", method=RequestMethod.GET)
    public @ResponseBody List<Person> getPersonDetails(HttpServletResponse response) {
        List<Person> listPerson = null;
        try {
            listPerson = getPersonList();
            if(!CollectionUtils.isEmpty(listPerson)) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.getWriter().write("Whatever you want");
            }
        } catch(final Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("Whatever you want");
        }
        return listPerson;
    }
    
  • 0

    从控制器方法中抛出特定异常 . 例如,在您的情况下,如果列表为空,则为自定义PersonNotFoundException,对于未知错误,为ServiceException . 并通过返回类型为ResponseEntity的@ExceptionHandlers处理这些异常 .

    控制器方法的返回类型应仅为List .

    这将有助于您获得整洁的文档 .

    尝试在spring中搜索如何使用ExceptionHandlers .

    希望这能回答你的问题 .

  • 1

    您可以创建JResponse类并将数据保存到 .

    public class JSonResponse{
      private Object result;
      private String statu;
    
      // 
    }
    
    
     @RequestMapping(value="/test", method=RequestMethod.GET)
     public @ResponseBody JSonResponse getPersonDetails() {
      JSonResponseres = new JSonResponse();
      List<Person> listPerson  = null;
      try {
        // Call to service and get the list of Person
        listPerson = getPersonList();
        if(CollectionUtils.isNotEmpty(listPerson)) {
            res.setResult(listPerson);
            res.status("SUCCESS");
         } else {
            res.setResult("Not Found Data");
            res.status("FAIL");
         }
      } catch(final Exception e) {
        // Return JSON object
        // {"ExceptionMessage":"Exception in controller."}
     }
    
      return res;
    }
    

相关问题