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

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

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

JsonNode.asInt介绍

[英]Method that will try to convert value of this node to a Java int. Numbers are coerced using default Java rules; booleans convert to 0 (false) and 1 (true), and Strings are parsed using default Java language integer parsing rules.

If representation cannot be converted to an int (including structured types like Objects and Arrays), default value of 0 will be returned; no exceptions are thrown.
[中]方法,该方法将尝试将此节点的值转换为Java int;布尔值转换为0(false)和1(true),字符串使用默认的Java语言整数解析规则进行解析。
如果表示无法转换为int(包括对象和数组等结构化类型),将返回默认值0;没有抛出异常。

代码示例

代码示例来源:origin: Graylog2/graylog2-server

private static int intValue(final JsonNode json, final String fieldName) {
  if (json != null) {
    final JsonNode value = json.get(fieldName);
    if (value != null) {
      return value.asInt(-1);
    }
  }
  return -1;
}

代码示例来源:origin: opentripplanner/OpenTripPlanner

@Override
public void configure(Graph graph, JsonNode config) throws Exception {
  frequencySec = config.path("frequencySec").asInt(5);
  url = config.path("url").asText();
  LOG.info("Configured example updater: frequencySec={} and url={}", frequencySec, url);
}

代码示例来源:origin: wuyouzhuguli/SpringAll

@RequestMapping("readjsonstring")
@ResponseBody
public String readJsonString() {
  try {
    String json = "{\"name\":\"mrbird\",\"age\":26}";
    JsonNode node = this.mapper.readTree(json);
    String name = node.get("name").asText();
    int age = node.get("age").asInt();
    return name + " " + age;
  } catch (Exception e) {
    e.printStackTrace();
  }
  return null;
}

代码示例来源:origin: linlinjava/litemall

public static Integer parseInteger(String body, String field) {
  ObjectMapper mapper = new ObjectMapper();
  JsonNode node = null;
  try {
    node = mapper.readTree(body);
    JsonNode leaf = node.get(field);
    if (leaf != null)
      return leaf.asInt();
  } catch (IOException e) {
    e.printStackTrace();
  }
  return null;
}

代码示例来源:origin: SeldonIO/seldon-server

public Request(JsonNode j)
{
  consumer = j.get("consumer").asText();
  time = j.get("time").asLong();
  httpmethod = j.get("httpmethod").asText();
  
  path = createPath(j.get("path").asText());
  exectime = j.get("exectime").asInt();
  count = 1;
}

代码示例来源:origin: opentripplanner/OpenTripPlanner

@Override
public void configure(Graph graph, JsonNode config) throws Exception {
  url = config.path("url").asText();
  feedId = config.path("feedId").asText("");
  reconnectPeriodSec = config.path("reconnectPeriodSec").asInt(DEFAULT_RECONNECT_PERIOD_SEC);
}

代码示例来源:origin: linlinjava/litemall

public static Short parseShort(String body, String field) {
  ObjectMapper mapper = new ObjectMapper();
  JsonNode node = null;
  try {
    node = mapper.readTree(body);
    JsonNode leaf = node.get(field);
    if (leaf != null) {
      Integer value = leaf.asInt();
      return value.shortValue();
    }
  } catch (IOException e) {
    e.printStackTrace();
  }
  return null;
}

代码示例来源:origin: apache/nifi

private RecordSchema createRecordSchema(final JsonNode schemaNode) throws SchemaNotFoundException {
  final String subject = schemaNode.get(SUBJECT_FIELD_NAME).asText();
  final int version = schemaNode.get(VERSION_FIELD_NAME).asInt();
  final int id = schemaNode.get(ID_FIELD_NAME).asInt();
  final String schemaText = schemaNode.get(SCHEMA_TEXT_FIELD_NAME).asText();
  try {
    final Schema avroSchema = new Schema.Parser().parse(schemaText);
    final SchemaIdentifier schemaId = SchemaIdentifier.builder().name(subject).id(Long.valueOf(id)).version(version).build();
    final RecordSchema recordSchema = AvroTypeUtil.createSchema(avroSchema, schemaText, schemaId);
    return recordSchema;
  } catch (final SchemaParseException spe) {
    throw new SchemaNotFoundException("Obtained Schema with id " + id + " and name " + subject
      + " from Confluent Schema Registry but the Schema Text that was returned is not a valid Avro Schema");
  }
}

代码示例来源:origin: Graylog2/graylog2-server

private static QueryParsingException buildQueryParsingException(Supplier<String> errorMessage,
                                JsonNode rootCause,
                                List<String> reasons) {
  final JsonNode lineJson = rootCause.path("line");
  final Integer line = lineJson.isInt() ? lineJson.asInt() : null;
  final JsonNode columnJson = rootCause.path("col");
  final Integer column = columnJson.isInt() ? columnJson.asInt() : null;
  final String index = rootCause.path("index").asText(null);
  return new QueryParsingException(errorMessage.get(), line, column, index, reasons);
}

代码示例来源:origin: linlinjava/litemall

public static Byte parseByte(String body, String field) {
  ObjectMapper mapper = new ObjectMapper();
  JsonNode node = null;
  try {
    node = mapper.readTree(body);
    JsonNode leaf = node.get(field);
    if (leaf != null) {
      Integer value = leaf.asInt();
      return value.byteValue();
    }
  } catch (IOException e) {
    e.printStackTrace();
  }
  return null;
}

代码示例来源:origin: apache/nifi

@Override
public RedisStateMap deserialize(final byte[] data) throws IOException {
  if (data == null || data.length == 0) {
    return null;
  }
  final RedisStateMap.Builder builder = new RedisStateMap.Builder();
  try (final JsonParser jsonParser = jsonFactory.createParser(data)) {
    final JsonNode rootNode = jsonParser.readValueAsTree();
    builder.version(rootNode.get(FIELD_VERSION).asLong());
    builder.encodingVersion(rootNode.get(FIELD_ENCODING).asInt());
    final JsonNode stateValuesNode = rootNode.get(FIELD_STATE_VALUES);
    stateValuesNode.fields().forEachRemaining(e -> builder.stateValue(e.getKey(), e.getValue().asText()));
  }
  return builder.build();
}

代码示例来源:origin: opentripplanner/OpenTripPlanner

public BikeRentalStation makeStation(JsonNode node) {
    if (!node.path("activate").asText().equals("1")) {
        return null;
    }
    BikeRentalStation station = new BikeRentalStation();
    station.id = String.format("%d", node.path("id").asInt());
    station.x = node.path("longitude").asDouble();
    station.y = node.path("latitude").asDouble();
    station.name = new NonLocalizedString(node.path("name").asText());
    station.bikesAvailable = node.path("dock_bikes").asInt();
    station.spacesAvailable = node.path("free_bases").asInt();
    return station;
}

代码示例来源:origin: aws/aws-sdk-java

/**
 * Parse the output from the credentials process.
 */
private JsonNode parseProcessOutput(String processOutput) {
  JsonNode credentialsJson = Jackson.jsonNodeOf(processOutput);
  if (!credentialsJson.isObject()) {
    throw new IllegalStateException("Process did not return a JSON object.");
  }
  JsonNode version = credentialsJson.get("Version");
  if (version == null || !version.isInt() || version.asInt() != 1) {
    throw new IllegalStateException("Unsupported credential version: " + version);
  }
  return credentialsJson;
}

代码示例来源:origin: apache/pulsar

@Override
  public Object getField(String fieldName) {
    JsonNode fn = jn.get(fieldName);
    if (fn.isContainerNode()) {
      AtomicInteger idx = new AtomicInteger(0);
      List<Field> fields = Lists.newArrayList(fn.fieldNames())
        .stream()
        .map(f -> new Field(f, idx.getAndIncrement()))
        .collect(Collectors.toList());
      return new GenericJsonRecord(fields, fn);
    } else if (fn.isBoolean()) {
      return fn.asBoolean();
    } else if (fn.isInt()) {
      return fn.asInt();
    } else if (fn.isFloatingPointNumber()) {
      return fn.asDouble();
    } else if (fn.isDouble()) {
      return fn.asDouble();
    } else {
      return fn.asText();
    }
  }
}

代码示例来源:origin: opentripplanner/OpenTripPlanner

/** Shared configuration code for all polling graph updaters. */
  @Override
  final public void configure (Graph graph, JsonNode config) throws Exception {
    pollingPeriodSeconds = config.path("frequencySec").asInt(60);
    type = config.path("type").asText("");
    // Additional configuration for the concrete subclass
    configurePolling(graph, config);
  }
}

代码示例来源:origin: joelittlejohn/jsonschema2pojo

@Override
public JFieldVar apply(String nodeName, JsonNode node, JsonNode parent, JFieldVar field, Schema currentSchema) {
  if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations()
      && (node.has("minItems") || node.has("maxItems"))) {
    JAnnotationUse annotation = field.annotate(Size.class);
    if (node.has("minItems")) {
      annotation.param("min", node.get("minItems").asInt());
    }
    if (node.has("maxItems")) {
      annotation.param("max", node.get("maxItems").asInt());
    }
  }
  return field;
}

代码示例来源:origin: apache/ignite

/**
 * @param content Content to check.
 */
private JsonNode jsonResponse(String content) throws IOException {
  assertNotNull(content);
  assertFalse(content.isEmpty());
  JsonNode node = JSON_MAPPER.readTree(content);
  assertFalse(node.get("affinityNodeId").asText().isEmpty());
  assertEquals(0, node.get("successStatus").asInt());
  assertTrue(node.get("error").isNull());
  assertTrue(node.get("sessionToken").isNull());
  return node.get("response");
}

代码示例来源:origin: Graylog2/graylog2-server

@GET
  @Timed
  @Path("/health")
  @ApiOperation(value = "Get cluster and shard health overview")
  @RequiresPermissions(RestPermissions.INDEXERCLUSTER_READ)
  @Produces(MediaType.APPLICATION_JSON)
  public ClusterHealth clusterHealth() {
    final JsonNode health = cluster.health()
        .orElseThrow(() -> new InternalServerErrorException("Couldn't read Elasticsearch cluster health"));
    final ClusterHealth.ShardStatus shards = ClusterHealth.ShardStatus.create(
        health.path("active_shards").asInt(),
        health.path("initializing_shards").asInt(),
        health.path("relocating_shards").asInt(),
        health.path("unassigned_shards").asInt());

    return ClusterHealth.create(health.path("status").asText().toLowerCase(Locale.ENGLISH), shards);
  }
}

代码示例来源:origin: joelittlejohn/jsonschema2pojo

@Override
public JFieldVar apply(String nodeName, JsonNode node, JsonNode parent, JFieldVar field, Schema currentSchema) {
  
  if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations()
      && (node.has("minLength") || node.has("maxLength"))) {
    JAnnotationUse annotation = field.annotate(Size.class);
    if (node.has("minLength")) {
      annotation.param("min", node.get("minLength").asInt());
    }
    if (node.has("maxLength")) {
      annotation.param("max", node.get("maxLength").asInt());
    }
  }
  return field;
}

代码示例来源:origin: apache/incubator-pinot

@Test
public void testJsonResponseWithoutSplitCommit() {
 SegmentCompletionProtocol.Response.Params params =
   new SegmentCompletionProtocol.Response.Params().withBuildTimeSeconds(BUILD_TIME_MILLIS).withOffset(OFFSET)
     .withSplitCommit(false).withStatus(SegmentCompletionProtocol.ControllerResponseStatus.COMMIT);
 SegmentCompletionProtocol.Response response = new SegmentCompletionProtocol.Response(params);
 JsonNode jsonNode = JsonUtils.objectToJsonNode(response);
 assertEquals(jsonNode.get("offset").asInt(), OFFSET);
 assertNull(jsonNode.get("segmentLocation"));
 assertFalse(jsonNode.get("isSplitCommitType").asBoolean());
 assertEquals(jsonNode.get("status").asText(), SegmentCompletionProtocol.ControllerResponseStatus.COMMIT.toString());
 assertNull(jsonNode.get("controllerVipUrl"));
}

相关文章