-2

首先,非常感谢您阅读这个问题。

我有一个 JPA 项目,一切正常,我用控制器得到的 json 是这种形式:

{"id": 1, "name": "Canada"},{"id": 2, "name": "USA"}

一切都很好,但我想用Jsend标准获得一个 json,它是这样的:

{
status : "success",
data : {
    "country" : [
        {"id": 1, "name": "Canada"},
        {"id": 2, "name": "USA"}
    ]
  }
}

{
  "status" : "fail",
  "data" : { "title" : "A title is required" }
}

{
 "status" : "error",
 "message" : "Unable to communicate with database"
}

正如你所看到的,我想要一个状态,显示成功、失败或错误:但我不知道该怎么做。这是我的 DTO、DAO 和控制器

@Entity
public class Country implements Serializable {

private static final long serialVersionUID = -7256468460105939L;

@Id
@Column(name="id")
private int id;

@Column(name="name")
private String name;

//Constructor, get and set 

@Repository
@Transactional
public class CountryRepository {

  @PersistenceContext
  EntityManager entityManager;

  public CountryDTO findById(int id) {
      return entityManager.find(CountryDTO.class, id);
  }
}

控制器

@RestController
public class CountryController {

    @Autowired
    CountryDTO repository;

    @RequestMapping(value="api/country/{id}", method=RequestMethod.GET)
    public @ResponseBody CountryDTO getByID(@PathVariable("id") int id){
        return repository.findById(id);
    }
}

再次感谢您的时间。

4

1 回答 1

-1

从我的角度来看,这是一个很好的问题。所以我可以给出实现这一目标的行动项目列表。

  1. 您应该知道@ControllerAdviceSpring 中可用的注释。
  2. 通过利用它,您可以使用您的响应对象。
  3. 然后你应该创建你自己的类似于 JSend 的对象。就我而言,我创建了JSendMessage

    public class JSendMessage {
        String status;
        String message;
        Object data;
        // Add getter and setter
    }
    
  4. 现在您应该使用@ControllerAdvice返回所需的对象来映射上面的类。

  5. 因此,无论何时出现异常,您都可以创建并发送您自己的自定义异常消息。这方面会有很多参考。只是寻找@ControllerAdvice
于 2018-03-26T04:49:44.717 回答