使用Jackson的ObjectNode.putObject进行方法链接 [英] Using Jackson’s ObjectNode.putObject for method chaining

查看:573
本文介绍了使用Jackson的ObjectNode.putObject进行方法链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

static String createRequestJson(String apiKey, String apiSecret) {
  JsonNodeFactory factory = JsonNodeFactory.instance;
  ObjectNode root = factory.objectNode();
  root.set("auth", factory.objectNode()
      .put("api_key", apiKey)
      .put("api_secret", apiSecret));
  root.put("wait", true);
  return root.toString();
}

它可以工作,但是代码看起来比必需的更为复杂.特别是,我想摆脱root变量.

It works, but the code looks more complicated than necessary. In particular, I’d like to get rid of the root variable.

static String createRequestJson(String apiKey, String apiSecret) {
  JsonNodeFactory factory = JsonNodeFactory.instance;
  return factory.objectNode()
      .set("auth", factory.objectNode()
          .put("api_key", apiKey)
          .put("api_secret", apiSecret))
      .put("wait", true) // Compile error: JsonNode.put(String, boolean) undefined
      .toString();
}

问题在于set方法不会返回ObjectNode,而只会返回JsonNode,这会中断方法链接.

The problem is that the set method does not return an ObjectNode but only a JsonNode, which breaks the method chaining.

我是否忽略了一些明显的东西,还是无法一劳永逸地创建这样的嵌套对象?

Did I overlook something obvious, or is it not possible to create such nested objects in one go?

推荐答案

这是方法签名中的一个不幸缺陷,但不幸的是,如果不破坏现有代码,则无法更改该缺陷:如果签名已更改(返回类型是一部分)签名),则任何使用此方法的现有代码都无法在Jackson的较新版本中加载.

This is an unfortunate flaw in method signature, but unfortunately one that is not possible to change without breakage for existing code: if signature was changed (return type is part of signature), any existing code using this method would fail to load with newer versions of Jackson.

所以,是的,这是一种错误,但不幸的是,它很难修复.

So, yes, it is a bug of sorts, but unfortunately one that is very difficult to fix.

这篇关于使用Jackson的ObjectNode.putObject进行方法链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆