com.fasterxml.jackson.databind.JsonNode.canConvertToInt()方法的使用及代码示例

x33g5p2x  于2022-01-21 转载在 其他  
字(11.7k)|赞(0)|评价(0)|浏览(180)

本文整理了Java中com.fasterxml.jackson.databind.JsonNode.canConvertToInt()方法的一些代码示例,展示了JsonNode.canConvertToInt()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。JsonNode.canConvertToInt()方法的具体详情如下:
包路径:com.fasterxml.jackson.databind.JsonNode
类名称:JsonNode
方法名:canConvertToInt

JsonNode.canConvertToInt介绍

[英]Method that can be used to check whether this node is a numeric node ( #isNumber would return true) AND its value fits within Java's 32-bit signed integer type, int. Note that floating-point numbers are convertible if the integral part fits without overflow (as per standard Java coercion rules)

NOTE: this method does not consider possible value type conversion from JSON String into Number; so even if this method returns false, it is possible that #asInt could still succeed if node is a JSON String representing integral number, or boolean.
[中]方法,该方法可用于检查此节点是否为数字节点(#isNumber将返回true),并且其值是否符合Java的32位带符号整数类型int。请注意,如果整数部分适合而没有溢出,则浮点数是可转换的(根据标准Java强制规则)
注意:此方法不考虑从JSON字符串转换为数字的可能值类型;所以,即使此方法返回false,如果节点是表示整数或布尔值的JSON字符串,则#asInt仍可能成功。

代码示例

代码示例来源:origin: java-json-tools/json-schema-validator

protected final ObjectNode digestedNumberNode(final JsonNode schema)
  {
    final ObjectNode ret = FACTORY.objectNode();

    final JsonNode node = schema.get(keyword);
    final boolean isLong = valueIsLong(node);
    ret.put("valueIsLong", isLong);

    if (isLong) {
      ret.put(keyword, node.canConvertToInt()
        ? FACTORY.numberNode(node.intValue())
        : FACTORY.numberNode(node.longValue()));
      return ret;
    }

    final BigDecimal decimal = node.decimalValue();
    ret.put(keyword, decimal.scale() == 0
      ? FACTORY.numberNode(decimal.toBigIntegerExact())
      : node);

    return ret;
  }
}

代码示例来源:origin: greenaddress/GreenBits

public static WampMessage fromObjectArray(ArrayNode messageNode)
    throws WampError {
  if (messageNode == null || messageNode.size() < 1
      || !messageNode.get(0).canConvertToInt())
    throw new WampError(ApplicationError.INVALID_MESSAGE);
  int messageType = messageNode.get(0).asInt();
  WampMessageFactory factory = messageFactories.get(messageType);
  if (factory == null)
    return null; // We can't find the message type, so we skip it
  return factory.fromObjectArray(messageNode);
}

代码示例来源:origin: net.thisptr/jackson-jq

@Override
  public List<JsonNode> apply(final Scope scope, final List<JsonQuery> args, final JsonNode in) throws JsonQueryException {
    Preconditions.checkInputArrayType("implode", in, JsonNodeType.NUMBER);

    final StringBuilder builder = new StringBuilder();
    for (final JsonNode ch : in) {
      if (ch.canConvertToInt()) {
        builder.append((char) ch.asInt());
      } else {
        throw new JsonQueryException("input to implode() must be a list of codepoints; " + ch.getNodeType() + " found");
      }
    }
    return Collections.<JsonNode> singletonList(new TextNode(builder.toString()));
  }
}

代码示例来源:origin: ws.wamp.jawampa/jawampa-core

public static WampMessage fromObjectArray(ArrayNode messageNode)
    throws WampError {
  if (messageNode == null || messageNode.size() < 1
      || !messageNode.get(0).canConvertToInt())
    throw new WampError(ApplicationError.INVALID_MESSAGE);
  int messageType = messageNode.get(0).asInt();
  WampMessageFactory factory = messageFactories.get(messageType);
  if (factory == null)
    return null; // We can't find the message type, so we skip it
  return factory.fromObjectArray(messageNode);
}

代码示例来源:origin: eiiches/jackson-jq

@Override
  public List<JsonNode> apply(final Scope scope, final List<JsonQuery> args, final JsonNode in) throws JsonQueryException {
    Preconditions.checkInputArrayType("implode", in, JsonNodeType.NUMBER);

    final StringBuilder builder = new StringBuilder();
    for (final JsonNode ch : in) {
      if (ch.canConvertToInt()) {
        builder.append((char) ch.asInt());
      } else {
        throw new JsonQueryException("input to implode() must be a list of codepoints; " + ch.getNodeType() + " found");
      }
    }
    return Collections.<JsonNode> singletonList(new TextNode(builder.toString()));
  }
}

代码示例来源:origin: Matthias247/jawampa

public static WampMessage fromObjectArray(ArrayNode messageNode)
    throws WampError {
  if (messageNode == null || messageNode.size() < 1
      || !messageNode.get(0).canConvertToInt())
    throw new WampError(ApplicationError.INVALID_MESSAGE);
  int messageType = messageNode.get(0).asInt();
  WampMessageFactory factory = messageFactories.get(messageType);
  if (factory == null)
    return null; // We can't find the message type, so we skip it
  return factory.fromObjectArray(messageNode);
}

代码示例来源:origin: com.linecorp.centraldogma/centraldogma-common

private static void validateRevisionNumber(DeserializationContext ctx, @Nullable JsonNode node,
                        String type, boolean zeroAllowed) throws JsonMappingException {
    if (node == null) {
      ctx.reportInputMismatch(Revision.class, "missing %s revision number", type);
      // Should never reach here.
      throw new Error();
    }

    if (!node.canConvertToInt() || !zeroAllowed && node.intValue() == 0) {
      ctx.reportInputMismatch(Revision.class,
                  "A %s revision number must be %s integer.",
                  type, zeroAllowed ? "an" : "a non-zero");
      // Should never reach here.
      throw new Error();
    }
  }
}

代码示例来源:origin: line/centraldogma

private static void validateRevisionNumber(DeserializationContext ctx, @Nullable JsonNode node,
                        String type, boolean zeroAllowed) throws JsonMappingException {
    if (node == null) {
      ctx.reportInputMismatch(Revision.class, "missing %s revision number", type);
      // Should never reach here.
      throw new Error();
    }

    if (!node.canConvertToInt() || !zeroAllowed && node.intValue() == 0) {
      ctx.reportInputMismatch(Revision.class,
                  "A %s revision number must be %s integer.",
                  type, zeroAllowed ? "an" : "a non-zero");
      // Should never reach here.
      throw new Error();
    }
  }
}

代码示例来源:origin: com.linecorp.centraldogma/centraldogma-common-shaded

private static void validateRevisionNumber(DeserializationContext ctx, @Nullable JsonNode node,
                        String type, boolean zeroAllowed) throws JsonMappingException {
    if (node == null) {
      ctx.reportInputMismatch(Revision.class, "missing %s revision number", type);
      // Should never reach here.
      throw new Error();
    }

    if (!node.canConvertToInt() || !zeroAllowed && node.intValue() == 0) {
      ctx.reportInputMismatch(Revision.class,
                  "A %s revision number must be %s integer.",
                  type, zeroAllowed ? "an" : "a non-zero");
      // Should never reach here.
      throw new Error();
    }
  }
}

代码示例来源:origin: net.thisptr/jackson-jq

@Override
public JsonNode apply(ObjectMapper mapper, JsonNode lhs, JsonNode rhs) throws JsonQueryException {
  if (lhs.isIntegralNumber() && rhs.isIntegralNumber()) {
    final long r = lhs.asLong() * rhs.asLong();
    return JsonNodeUtils.asNumericNode(r);
  } else if (lhs.isNumber() && rhs.isNumber()) {
    final double r = lhs.asDouble() * rhs.asDouble();
    return JsonNodeUtils.asNumericNode(r);
  } else if (lhs.isTextual() && rhs.canConvertToInt()) {
    final int count = rhs.asInt();
    if (count <= 0)
      return NullNode.getInstance();
    return new TextNode(Strings.repeat(lhs.asText(), count));
  } else if (lhs.isObject() && rhs.isObject()) {
    return mergeRecursive(mapper, (ObjectNode) lhs, (ObjectNode) rhs);
  } else {
    throw new JsonQueryTypeException(lhs, rhs, "cannot be multiplied");
  }
}

代码示例来源:origin: org.kitchen-eel/json-schema-validator

@Override
  public void checkValue(final SyntaxValidator validator,
    final List<Message> messages, final JsonNode schema)
  {
    final JsonNode node = schema.get(keyword);
    final Message.Builder msg = newMsg().addInfo("found", node);

    if (!node.canConvertToInt()) {
      msg.setMessage("integer value is too large")
        .addInfo("max", Integer.MAX_VALUE);
      messages.add(msg.build());
      return;
    }

    if (node.intValue() < 0)
      messages.add(msg.setMessage("value cannot be negative").build());
  }
}

代码示例来源:origin: org.apache.beam/beam-sdks-java-core

/**
 * Extracts int value from JsonNode if it is within bounds.
 *
 * <p>Throws {@link UnsupportedRowJsonException} if value is out of bounds.
 */
static ValueExtractor<Integer> intValueExtractor() {
 return ValidatingValueExtractor.<Integer>builder()
   .setExtractor(JsonNode::intValue)
   .setValidator(jsonNode -> jsonNode.isIntegralNumber() && jsonNode.canConvertToInt())
   .build();
}

代码示例来源:origin: com.github.bjansen/swagger-schema-validator

@Override
  public void validate(final ProcessingReport report,
             final MessageBundle bundle,
             final FullData data) throws ProcessingException {
    final JsonNode instance = data.getInstance().getNode();

    if (!instance.canConvertToInt()) {
      report.warn(newMsg(data, bundle, "warn.format.int32.overflow")
        .put("key", "warn.format.int32.overflow")
        .putArgument("value", instance));
    }
  }
}

代码示例来源:origin: com.atlassian.oai/swagger-request-validator-core

@Override
  public void validate(final ProcessingReport report,
             final MessageBundle bundle,
             final FullData data) throws ProcessingException {
    final JsonNode instance = data.getInstance().getNode();

    if (!instance.canConvertToInt()) {
      report.warn(newMsg(data, bundle, "warn.format.int32.overflow")
          .put("key", "warn.format.int32.overflow")
          .putArgument("value", instance));
    }
  }
}

代码示例来源:origin: org.apache.beam/beam-sdks-java-core

/**
 * Extracts float value from JsonNode if it is within bounds.
 *
 * <p>Throws {@link UnsupportedRowJsonException} if value is out of bounds.
 */
static ValueExtractor<Float> floatValueExtractor() {
 return ValidatingValueExtractor.<Float>builder()
   .setExtractor(JsonNode::floatValue)
   .setValidator(
     jsonNode ->
       jsonNode.isFloat()
         // Either floating number which allows lossless conversion to float
         || (jsonNode.isFloatingPointNumber()
           && jsonNode.doubleValue() == (double) (float) jsonNode.doubleValue())
         // Or an integer number which allows lossless conversion to float
         || (jsonNode.isIntegralNumber()
           && jsonNode.canConvertToInt()
           && jsonNode.asInt() == (int) (float) jsonNode.asInt()))
   .build();
}

代码示例来源:origin: com.box/json-schema-core

@Override
  protected void checkValue(final Collection<JsonPointer> pointers,
    final MessageBundle bundle, final ProcessingReport report,
    final SchemaTree tree)
    throws ProcessingException
  {
    final JsonNode node = getNode(tree);

    if (!node.canConvertToInt()) {
      report.error(newMsg(tree, bundle, "common.integerTooLarge")
        .put("max", Integer.MAX_VALUE));
      return;
    }

    if (node.intValue() < 0)
      report.error(newMsg(tree, bundle, "common.integerIsNegative"));
  }
}

代码示例来源:origin: com.github.fge/json-schema-core

@Override
  protected void checkValue(final Collection<JsonPointer> pointers,
    final MessageBundle bundle, final ProcessingReport report,
    final SchemaTree tree)
    throws ProcessingException
  {
    final JsonNode node = getNode(tree);

    if (!node.canConvertToInt()) {
      report.error(newMsg(tree, bundle, "common.integerTooLarge")
        .put("max", Integer.MAX_VALUE));
      return;
    }

    if (node.intValue() < 0)
      report.error(newMsg(tree, bundle, "common.integerIsNegative"));
  }
}

代码示例来源:origin: java-json-tools/json-schema-core

@Override
  protected void checkValue(final Collection<JsonPointer> pointers,
    final MessageBundle bundle, final ProcessingReport report,
    final SchemaTree tree)
    throws ProcessingException
  {
    final JsonNode node = getNode(tree);

    if (!node.canConvertToInt()) {
      report.error(newMsg(tree, bundle, "common.integerTooLarge")
        .put("max", Integer.MAX_VALUE));
      return;
    }

    if (node.intValue() < 0)
      report.error(newMsg(tree, bundle, "common.integerIsNegative"));
  }
}

代码示例来源:origin: org.apache.beam/beam-sdks-java-core

/**
 * Extracts byte value from JsonNode if it is within bounds.
 *
 * <p>Throws {@link UnsupportedRowJsonException} if value is out of bounds.
 */
static ValueExtractor<Byte> byteValueExtractor() {
 return ValidatingValueExtractor.<Byte>builder()
   .setExtractor(jsonNode -> (byte) jsonNode.intValue())
   .setValidator(
     jsonNode ->
       jsonNode.isIntegralNumber()
         && jsonNode.canConvertToInt()
         && jsonNode.intValue() >= Byte.MIN_VALUE
         && jsonNode.intValue() <= Byte.MAX_VALUE)
   .build();
}

代码示例来源:origin: org.apache.beam/beam-sdks-java-core

/**
 * Extracts short value from JsonNode if it is within bounds.
 *
 * <p>Throws {@link UnsupportedRowJsonException} if value is out of bounds.
 */
static ValueExtractor<Short> shortValueExtractor() {
 return ValidatingValueExtractor.<Short>builder()
   .setExtractor(jsonNode -> (short) jsonNode.intValue())
   .setValidator(
     jsonNode ->
       jsonNode.isIntegralNumber()
         && jsonNode.canConvertToInt()
         && jsonNode.intValue() >= Short.MIN_VALUE
         && jsonNode.intValue() <= Short.MAX_VALUE)
   .build();
}

相关文章