格式化JSON结果表达式

时间:2016-03-23 13:19:49

标签: json spring rest jaxb jersey-2.0

我正在使用Jersey2和Spring编写REST api,我希望将生成的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;
}

1 个答案:

答案 0 :(得分:0)

我建议您创建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。这是我想要使用的列表对象,它包含有关我在客户端中用于分页的列表的元数据:http://pastebin.com/mTU4qbc7