【问题标题】:Remove method name from posted comment从发布的评论中删除方法名称
【发布时间】:2019-03-06 10:44:28
【问题描述】:

我编写了一个代码,在我的 localhost:3000 上添加了 cmets,但它解析了很多我想删除“commentModel”的信息,但是如果我从 CommentRq 类中删除它,我会收到错误

评论示例: { "commentModel": { "comment": "komentarz", "date": "3/6/19 9:34 AM" }, "id": 1}

我希望它是 { "comment": "komentarz", "date": "3/6/19 9:34 AM" }, "id": 1 }

评论请求

@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
public class CommentRq {



    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    private CommentModel commentModel;
    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    @Builder
    public static class CommentModel {
        @JsonProperty("comment")
        String resourceName;

        @JsonProperty("date")
        String resourceNamed;
    }

}

评论正文

public class CommentBody {

    Date now = new Date();
    @JsonInclude(JsonInclude.Include.NON_NULL)
    public CommentRq RequestCommentBody() {
        return CommentRq.builder()
                .commentModel(new CommentRq.CommentModel(
                        "komentarz",
                        (DateFormat.getInstance().format(now))

                ))
                .build();
    }
}

我在这里创建评论

Interface.PostComment postComment = Feign.builder()
            .client(new OkHttpClient())
            .encoder(new JacksonEncoder())
            .decoder(new JacksonDecoder())
            .logger(new Slf4jLogger(Interface.PostComment.class))
            .logLevel(Logger.Level.FULL)
            .target(Interface.PostComment.class, "http://localhost:3000/comments/");

    @When("i try to add a comment")
    public void postComment() {
        Map<String, Object> headermap = new HashMap<>();
        headermap.put("Content-Type", "application/json");
        CommentBody requestComment = new CommentBody();
        CommentRes commentRes = postComment.postComment(headermap, requestComment.RequestCommentBody());
        id = commentRes.getId();
        LOGGER.info("Created: " + DateFormat.getInstance().format(now));
    }

【问题讨论】:

  • 能否告诉我们您遇到了哪些错误
  • 当我删除私有 CommentModel commentModel 时无法解析方法'commentModel(testyLocalhost.CommentRq.CommentModel)';来自 CommentRq

标签: java lombok feign


【解决方案1】:

您可以使用@JsonUnwrapped 注释您的private CommentModel commentModel。它将打开您的 commentModel 对象并将其字段写入 json 的根目录。这将处理您的具体情况。但是您也可以修改您的请求结构:将 CommentModel 字段放入 CommentRq 并将 CommentModel 对象映射到 CommentRq 对象。

【讨论】:

  • 感谢回复,但 @JsonUnwrapped 不起作用,我不确定如何做你提到的第二件事,你能给我代码吗?
  • 它应该可以工作。请删除@JsonProperty 注释并添加@JsonUnwrapped
  • 是的,它的工作我还需要在其他地方添加它
  • 第二个选项是不要嵌入CommentModel对象,而有CommentRq这样public class CommentRq { @JsonProperty("comment") String resourceName; @JsonProperty("date") String resourceNamed; }
猜你喜欢
  • 2011-12-18
  • 2015-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多