【问题标题】:How to correctly use Jackson, Dropwizard and JSON patterns如何正确使用 Jackson、Dropwizard 和 JSON 模式
【发布时间】: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


【解决方案1】:

您应该从您的对象公开什么样的“行为”以及您希望 API 如何公开开始。 尽管没有灵丹妙药,但仍有大量文献可以指导您正确地为 API(以及对象)建模

这里有几个链接:

就个人而言,一般来说,我创建 POJO,但就像 @cricket_007 提到的那样,它有点固执己见。

HTH。

【讨论】:

    猜你喜欢
    • 2014-07-23
    • 2021-11-16
    • 2016-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    相关资源
    最近更新 更多