我正在使用Jersey2和Spring编写REST,我希望将生成的JSON表达式格式化为更特殊的东西,我不知道是修改POJO的结构还是在重新源上格式化响应
实际JSON
Response [ {
"rcId" : 22900,
"posId" : 595,
"status" : "PERC6",
"dateFrom" : 1438380000000,
"dateTo" : 1442095200000,
"creaDate" : 1442349754000
"createdBy": "52e28419-2c48-526d-8e7c-783cf331e071",
"modifiedBy": "52e28419-1725-84bd-9884-6969e7b9b876",
} ]通缉格式的JSON
Response [ {
“results”: {
"rcId" : 22900,
"posId" : 595,
"status" : "PERC6",
"dateFrom" : 1438380000000,
"dateTo" : 1442095200000,
"creaDate" : 1442349754000
"createdBy": "52e28419-2c48-526d-8e7c-783cf331e071",
"modifiedBy": "52e28419-1725-84bd-9884-6969e7b9b876",
}
"related": {
"52e28419-2c48-526d-8e7c-783cf331e071": { "user/username" : "test" }
"52e28419-1725-84bd-9884-6969e7b9b876": { “user/username” : “test” }
}
"errors": [ ... If errors while executing query... ]
}我的对象看起来像这样
@Entity
@Table(name="STATUS")
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class RcPosStatus implements Serializable {
private static final long serialVersionUID = -8039686696076337853L;
@Id
@Column(name="RC_ID")
@XmlElement(name = "RC_ID")
private Long rcId;
@Column(name="POS_ID")
@XmlElement(name = "POS_ID")
private Long posId;
@Column(name="STATUS")
@XmlElement(name = "STATUS")
private String status;
@Column(name="DATE_FROM")
@XmlElement(name = "DATE_FROM")
private Date dateFrom;
@Column(name="DATE_TO")
@XmlElement(name = "DATE_TO")
private Date dateTo;
@Column(name="CREA_DATE")
@XmlElement(name = "CREATION_DATE")
private Date creaDate; 我的资源
@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<RcPosStatus> getRcPosStatus(
@QueryParam("orderByInsertionDate") String orderByInsertionDate,
@QueryParam("numberDaysToLookBack") Integer numberDaysToLookBack)
throws IOException, AppException {
List<RcPosStatus> status = statusService.getRcPosStatus(
orderByInsertionDate, numberDaysToLookBack);
return status;
}发布于 2016-03-24 00:41:26
我建议您创建DTO(数据传输对象)。不应更改数据模型以表示REST端点的结果。之所以如此,是因为客户端的需求随着时间的推移而变化,重要的是要有一个稳定的可靠模型。
这是一个架构问题,您希望如何组织DTO,下面是一个示例,如果我理解您的模型是正确的:
public class DefaultResponseDTO<Foo, Bar> implements Serializable {
private ArrayList<Foo> results;
private ArrayList<Bar> related;
private ArrayList<Errors> errors;
...
}现在使用它来创建您想要的响应
... //fetches data from resources and starting to map response.
DefaultResponseDTO<Pojo, Pojo> response = new DefaultResponseDTO();
response.results = results; //some results you want to return, Entities
response.related = releated; //some results you want to return as related, Entities
response.errors = errors;
return response; 使用泛型可以让您创建一个符合您需要的默认响应,并帮助您保持一个干净整洁的API。下面是我喜欢使用的list对象,它包含关于我在客户端中用于分页的列表的元数据:http://pastebin.com/mTU4qbc7
https://stackoverflow.com/questions/36179333
复制相似问题