【问题标题】:java jpa json standardjava jpa json标准
【发布时间】:2018-09-04 02:57:30
【问题描述】:

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

我有一个 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);
    }
}

再次感谢您的宝贵时间。

【问题讨论】:

    标签: java json jpa jsend


    【解决方案1】:

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

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

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

    5. 因此,无论何时出现异常,您都可以创建并发送您自己的自定义异常消息。 这方面会有很多参考。只需寻找@ControllerAdvice

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-18
      • 2018-07-13
      • 2011-10-17
      • 2013-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多