如何正确使用 Jackson、Dropwizard 和 JSON 模式

How to correctly use Jackson, Dropwizard and JSON patterns

我正在尝试如何构建我的 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
}

我可以用 post 创建这个对象,例如:

{
    "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"
      ]
   }
}

问题: 正在创建多个 类,就像我使用 optimal/correct 创建嵌套 JSON 对象的方式一样,我是否应该按照 [=45] 尝试将其全部包装在 "data:" 中=] 以上说明是必须做的吗?如果是这种情况,我应该创建一个名为 Data 的包含 Page 对象的 POJO 吗?

在查找有关此类信息的信息时,我似乎只能找到人们询问如何将 JSON 反序列化为 POJO,这不是我要找的内容。

真的很想在这里找到一些编写 API 的最佳实践。

然后你应该从你的对象公开什么样的 'behavior' 以及你希望你的 API 如何公开开始。 虽然没有灵丹妙药,但有大量文献可以指导您正确地建模 API(进而建模您的对象)

这里有几个链接:

就我个人而言,一般来说,我创建了 POJO,但就像@cricket_007 提到的那样,它有点自以为是。

HTH.