【发布时间】:2016-06-04 19:53:36
【问题描述】:
我正在尝试如何构建我的 JSON 对象以最好地符合http://jsonapi.org/format/
如果我使用以下类:
页面(主要对象)
public class Page {
@Id
@ObjectId
private String id; //Used for mongodb
@JsonProperty
private String type;
@JsonProperty
private Attribute attributes;
@JsonProperty
private Meta meta;
public Page() {
// Jackson deserialization
}
// Getters and setters
}
属性(嵌套在页面中)
public class Attribute {
@JsonProperty
private Date created = new Date();
@JsonProperty
private String title;
@JsonProperty
private String body;
public Attribute() {
// Jackson deserialization
}
public Attribute(Date created, String title, String body) {
this.created = created;
this.title = title;
this.body = body;
}
// Getters and setters
}
元(嵌套在页面中)
public class Meta {
@JsonProperty
private List<String> authors;
public Meta() {
}
public Meta(List<String> authors) {
this.authors = authors;
}
// Getters and setters
}
我可以使用以下帖子创建此对象:
{
"type": "page",
"attributes": {
"title": "This is the title",
"body": "<p>This is a long section of html, other stuff</p>"
},
"meta": {
"authors": [
"Steve",
"John",
"Sam"
]
}
}
并创建生成的 JSON 对象:
{
id:"56cbed5036f66b05dc2df841",
type:"page",
attributes:{
created:1456205138886,
title:"This is the title",
body:"<p>This is a long section of html, other stuff</p>"
},
meta:{
authors:[
"Steve",
"John",
"Sam"
]
}
}
问题: 是否以我拥有创建嵌套 JSON 对象的最佳/正确方式的方式创建多个类,我是否应该按照上面的链接将这一切都包装在“数据:”中,这是必须做的吗?如果是这种情况,我应该创建一个名为 Data 的 POJO,其中包含 Page 对象吗?
在寻找有关此类事物的信息时,我似乎能找到的只是人们询问如何将 JSON 反序列化为 POJO,这不是我想要的。
真的很想在这里找到一些编写 API 的最佳实践。
【问题讨论】:
-
为了序列化嵌套的 JSON,需要为每个 JSON 对象定义一个类。就最佳实践而言,这有点自以为是
标签: java json api jackson dropwizard