Java Code Examples for com.fasterxml.jackson.databind.JsonNode#asInt()

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#asInt() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MahutaCustomRepositoryImpl.java    From Mahuta with Apache License 2.0 6 votes vote down vote up
/**
 * Deserialize a JSONNode to a primitive object
 *
 * @param node JSON node
 * @return primitive object
 */
public static Object deserialize(JsonNode node) {

    if (node == null || node.isMissingNode() || node.isNull()) {
        return ""; // Because toMap doesn't accept null value ...
    } else if (node.isBoolean()) {
        return node.asBoolean();
    } else if (node.isLong()) {
        return node.asLong();
    } else if (node.isInt()) {
        return node.asInt();
    } else if (node.isDouble()) {
        return node.asDouble();
    } else if (node.isArray()) {
        return StreamSupport
                .stream(Spliterators.spliteratorUnknownSize(node.elements(), Spliterator.ORDERED), false)
                .map(MahutaCustomRepositoryImpl::deserialize).collect(Collectors.toList());
    } else {
        return node.asText();
    }
}
 
Example 2
Source File: JsonQueryParser.java    From searchbox-core with Apache License 2.0 6 votes vote down vote up
private Object getFieldValue(JsonNode fieldValue){
	Object val;
	
	if(fieldValue.isTextual())
		val = fieldValue.asText();
	else if(fieldValue.isInt())
		val = fieldValue.asInt();
	else if(fieldValue.isDouble())
		val = fieldValue.asDouble();
	else if(fieldValue.isBoolean())
		val = fieldValue.asBoolean();
	else
		val = null;
	
	return val;
}
 
Example 3
Source File: JawboneDataPointMapper.java    From shimmer with Apache License 2.0 6 votes vote down vote up
/**
 * Translates a time zone descriptor from one of various representations (Olson, seconds offset, GMT offset) into a
 * {@link ZoneId}.
 *
 * @param timeZoneValueNode the value associated with a timezone property
 */
static ZoneId parseZone(JsonNode timeZoneValueNode) {

    // default to UTC if timezone is not present
    if (timeZoneValueNode.isNull()) {
        return ZoneOffset.UTC;
    }

    // "-25200"
    if (timeZoneValueNode.asInt() != 0) {
        ZoneOffset zoneOffset = ZoneOffset.ofTotalSeconds(timeZoneValueNode.asInt());

        // TODO confirm if this is even necessary, since ZoneOffset is a ZoneId
        return ZoneId.ofOffset("GMT", zoneOffset);
    }

    // e.g., "GMT-0700" or "America/Los_Angeles"
    if (timeZoneValueNode.isTextual()) {
        return ZoneId.of(timeZoneValueNode.textValue());
    }

    throw new IllegalArgumentException(format("The time zone node '%s' can't be parsed.", timeZoneValueNode));
}
 
Example 4
Source File: ModelLoader.java    From aws-sdk-java-resources with Apache License 2.0 6 votes vote down vote up
/**
 * Loads a model from an arbitrary {@code InputStream}.
 */
public static ModelLoader load(InputStream stream) throws IOException {
    JsonNode tree = MAPPER.readTree(stream);
    JsonNode version = tree.get("FormatVersion");
    if (version == null || !version.isObject()) {
        throw new IllegalStateException("No FormatVersion found");
    }

    JsonNode major = version.get("Major");
    if (major == null || !major.isNumber()) {
        throw new IllegalStateException("No Major version found");
    }

    int majorVersion = major.asInt();

    switch (majorVersion) {
    case 1:
        return new ModelLoader(loadV1Model(tree, version));

    default:
        throw new IllegalStateException(
                "Unknown major version " + majorVersion + ". Perhaps "
                + "you need a newer version of the resources runtime?");
    }
}
 
Example 5
Source File: ByteObjectIOProvider.java    From constellation with Apache License 2.0 5 votes vote down vote up
@Override
public void readObject(final int attributeId, final int elementId, final JsonNode jnode, 
        final GraphWriteMethods graph, final Map<Integer, Integer> vertexMap, final Map<Integer, Integer> transactionMap, 
        final GraphByteReader byteReader, final ImmutableObjectCache cache) throws IOException {
    final Byte attributeValue = jnode.isNull() ? null : (byte) jnode.asInt();
    graph.setObjectValue(attributeId, elementId, attributeValue);
}
 
Example 6
Source File: JacksonUtil.java    From mall with MIT License 5 votes vote down vote up
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;
}
 
Example 7
Source File: KsqlJsonDeserializer.java    From ksql-fork-with-deep-learning-function with Apache License 2.0 5 votes vote down vote up
private Object enforceFieldType(Schema fieldSchema, JsonNode fieldJsonNode) {

    if (fieldJsonNode.isNull()) {
      return null;
    }
    switch (fieldSchema.type()) {
      case BOOLEAN:
        return fieldJsonNode.asBoolean();
      case INT32:
        return fieldJsonNode.asInt();
      case INT64:
        return fieldJsonNode.asLong();
      case FLOAT64:
        return fieldJsonNode.asDouble();
      case STRING:
        if (fieldJsonNode.isTextual()) {
          return fieldJsonNode.asText();
        } else {
          return fieldJsonNode.toString();
        }
      case ARRAY:
        return handleArray(fieldSchema, (ArrayNode) fieldJsonNode);
      case MAP:
        return handleMap(fieldSchema, fieldJsonNode);
      default:
        throw new KsqlException("Type is not supported: " + fieldSchema.type());
    }
  }
 
Example 8
Source File: JacksonUtil.java    From mall with MIT License 5 votes vote down vote up
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;
}
 
Example 9
Source File: OchSignalCodec.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an instance of {@link OchSignal} from JSON representation.
 *
 * @param obj JSON Object representing OchSignal
 * @return OchSignal
 * @throws IllegalArgumentException - if JSON object is ill-formed
 * @see OchSignalCodec#encode(OchSignal)
 */
public static OchSignal decode(ObjectNode obj) {
    final GridType gridType;
    final ChannelSpacing channelSpacing;
    final int spacingMultiplier;
    final int slotGranularity;

    String s;
    s = obj.get("channelSpacing").textValue();
    checkArgument(s != null, "ill-formed channelSpacing");
    channelSpacing = Enum.valueOf(ChannelSpacing.class, s);

    s = obj.get("gridType").textValue();
    checkArgument(s != null, "ill-formed gridType");
    gridType = Enum.valueOf(GridType.class, s);

    JsonNode node;
    node = obj.get("spacingMultiplier");
    checkArgument(node.canConvertToInt(), "ill-formed spacingMultiplier");
    spacingMultiplier = node.asInt();

    node = obj.get("slotGranularity");
    checkArgument(node.canConvertToInt(), "ill-formed slotGranularity");
    slotGranularity = node.asInt();

    return new OchSignal(gridType, channelSpacing, spacingMultiplier, slotGranularity);
}
 
Example 10
Source File: JacksonUtil.java    From yshopmall with Apache License 2.0 5 votes vote down vote up
public static Integer parseInteger(String body, String field) {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node;
    try {
        node = mapper.readTree(body);
        JsonNode leaf = node.get(field);
        if (leaf != null)
            return leaf.asInt();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}
 
Example 11
Source File: JsonUtil.java    From iceberg with Apache License 2.0 5 votes vote down vote up
public static Integer getIntOrNull(String property, JsonNode node) {
  if (!node.has(property)) {
    return null;
  }
  JsonNode pNode = node.get(property);
  Preconditions.checkArgument(pNode != null && !pNode.isNull() && pNode.isIntegralNumber() && pNode.canConvertToInt(),
      "Cannot parse %s from non-string value: %s", property, pNode);
  return pNode.asInt();
}
 
Example 12
Source File: JacksonUtil.java    From dts-shop with GNU Lesser General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 13
Source File: SyncTokenDeserializer.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public SyncToken deserialize(final JsonParser jp, final DeserializationContext ctx)
        throws IOException {

    ObjectNode tree = jp.readValueAsTree();

    Object value = null;
    if (tree.has("value")) {
        JsonNode node = tree.get("value");
        if (node.isBoolean()) {
            value = node.asBoolean();
        } else if (node.isDouble()) {
            value = node.asDouble();
        } else if (node.isLong()) {
            value = node.asLong();
        } else if (node.isInt()) {
            value = node.asInt();
        } else {
            value = node.asText();
        }

        if (value instanceof String) {
            String base64 = (String) value;
            try {
                value = Base64.getDecoder().decode(base64);
            } catch (RuntimeException e) {
                value = base64;
            }
        }
    }

    return new SyncToken(Objects.requireNonNull(value));
}
 
Example 14
Source File: CassandraPersistenceUtils.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public static Object toStorableValue( Object obj ) {
    if ( obj == null ) {
        return null;
    }

    if ( isBasicType( obj.getClass() ) ) {
        return obj;
    }

    if ( obj instanceof ByteBuffer ) {
        return obj;
    }

    JsonNode json = toJsonNode( obj );
    if ( ( json != null ) && json.isValueNode() ) {
        if ( json.isBigInteger() ) {
            return json.asInt();
        }
        else if ( json.isNumber() || json.isBoolean() ) {
            return BigInteger.valueOf( json.asLong() );
        }
        else if ( json.isTextual() ) {
            return json.asText();
        }
        else if ( json.isBinary() ) {
            try {
                return wrap( json.binaryValue() );
            }
            catch ( IOException e ) {
            }
        }
    }

    return json;
}
 
Example 15
Source File: ShapeModelReflector.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private Object getSimpleMemberValue(JsonNode currentNode, MemberModel memberModel) {
    if (memberModel.getHttp().getIsStreaming()) {
        return null;
    }
    switch (memberModel.getVariable().getSimpleType()) {
        case "Long":
            return currentNode.asLong();
        case "Integer":
            return currentNode.asInt();
        case "String":
            return currentNode.asText();
        case "Boolean":
            return currentNode.asBoolean();
        case "Double":
            return currentNode.asDouble();
        case "Instant":
            return Instant.ofEpochMilli(currentNode.asLong());
        case "SdkBytes":
            return SdkBytes.fromUtf8String(currentNode.asText());
        case "Float":
            return (float) currentNode.asDouble();
        case "Character":
            return asCharacter(currentNode);
        case "BigDecimal":
            return new BigDecimal(currentNode.asText());
        default:
            throw new IllegalArgumentException(
                    "Unsupported fieldType " + memberModel.getVariable().getSimpleType());
    }
}
 
Example 16
Source File: BasicURLFilter.java    From storm-crawler with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(Map stormConf, JsonNode filterParams) {
    JsonNode repet = filterParams.get("maxPathRepetition");
    if (repet != null) {
        maxPathRepetition = repet.asInt(3);
    }

    JsonNode length = filterParams.get("maxLength");
    if (length != null) {
        maxLength = length.asInt(-1);
    }
}
 
Example 17
Source File: ShortObjectIOProvider.java    From constellation with Apache License 2.0 5 votes vote down vote up
@Override
public void readObject(final int attributeId, final int elementId, final JsonNode jnode, 
        final GraphWriteMethods graph, final Map<Integer, Integer> vertexMap, final Map<Integer, Integer> transactionMap, 
        final GraphByteReader byteReader, final ImmutableObjectCache cache) throws IOException {
    final Short attributeValue = jnode.isNull() ? null : (short) jnode.asInt();
    graph.setObjectValue(attributeId, elementId, attributeValue);
}
 
Example 18
Source File: AbstractConverter.java    From elucidate-server with MIT License 4 votes vote down vote up
private NumericNode processNumericNode(JsonNode numericNode) {

        int value = numericNode.asInt();
        return JsonNodeFactory.instance.numberNode(value);
    }
 
Example 19
Source File: MaintenanceAssociationCodec.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Decodes the MaintenanceAssociation entity from JSON.
 *
 * @param json    JSON to decode
 * @param context decoding context
 * @param mdNameLen the length of the corresponding MD's name
 * @return decoded MaintenanceAssociation
 * @throws java.lang.UnsupportedOperationException if the codec does not
 *                                                 support decode operations
 */
public MaintenanceAssociation decode(ObjectNode json, CodecContext context, int mdNameLen) {
    if (json == null || !json.isObject()) {
        return null;
    }

    JsonNode maNode = json.get(MA);

    String maName = nullIsIllegal(maNode.get(MA_NAME), "maName is required").asText();
    String maNameType = MaIdShort.MaIdType.CHARACTERSTRING.name();
    if (maNode.get(MA_NAME_TYPE) != null) {
        maNameType = maNode.get(MA_NAME_TYPE).asText();
    }

    try {
        MaIdShort maId = MdMaNameUtil.parseMaName(maNameType, maName);
        MaBuilder builder =
                DefaultMaintenanceAssociation.builder(maId, mdNameLen);

        JsonNode maNumericIdNode = maNode.get(MA_NUMERIC_ID);
        if (maNumericIdNode != null) {
            short mdNumericId = (short) maNumericIdNode.asInt();
            builder = builder.maNumericId(mdNumericId);
        }
        if (maNode.get(CCM_INTERVAL) != null) {
            builder.ccmInterval(CcmInterval.valueOf(maNode.get(CCM_INTERVAL).asText()));
        }

        List<Component> componentList = (new ComponentCodec()).decode((ArrayNode)
                nullIsIllegal(maNode.get(COMPONENT_LIST),
                        "component-list is required"), context);
        for (Component component:componentList) {
            builder = builder.addToComponentList(component);
        }

        JsonNode rmepListJson = maNode.get(RMEP_LIST);
        if (rmepListJson != null) {
            List<MepId> remoteMeps = (new RMepCodec()).decode(
                    (ArrayNode) rmepListJson, context);
            for (MepId remoteMep:remoteMeps) {
                builder = builder.addToRemoteMepIdList(remoteMep);
            }
        }

        return builder.build();
    } catch (CfmConfigException e) {
        throw new IllegalArgumentException(e);
    }

}
 
Example 20
Source File: OpenstackVtapCriterionJsonMatcher.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
protected boolean matchesSafely(JsonNode jsonNode, Description description) {

    // check source IP address
    JsonNode jsonSrcIp = jsonNode.get(SRC_IP);
    String srcIp = criterion.srcIpPrefix().address().toString();
    if (!jsonSrcIp.asText().equals(srcIp)) {
        description.appendText("Source IP address was " + jsonSrcIp);
        return false;
    }

    // check destination IP address
    JsonNode jsonDstIp = jsonNode.get(DST_IP);
    String dstIp = criterion.dstIpPrefix().address().toString();
    if (!jsonDstIp.asText().equals(dstIp)) {
        description.appendText("Destination IP address was " + jsonDstIp);
        return false;
    }

    // check IP protocol
    JsonNode jsonIpProto = jsonNode.get(IP_PROTOCOL);
    if (jsonIpProto != null) {
        String ipProto = getProtocolStringFromType(criterion.ipProtocol());
        if (!jsonIpProto.asText().equals(ipProto)) {
            description.appendText("IP protocol was " + jsonIpProto);
            return false;
        }
    }

    // check source port number
    JsonNode jsonSrcPort = jsonNode.get(SRC_PORT);
    if (jsonSrcPort != null) {
        int srcPort = criterion.srcTpPort().toInt();
        if (jsonSrcPort.asInt() != srcPort) {
            description.appendText("Source port number was " + jsonSrcPort);
            return false;
        }
    }

    // check destination port number
    JsonNode jsonDstPort = jsonNode.get(DST_PORT);
    if (jsonDstPort != null) {
        int dstPort = criterion.dstTpPort().toInt();
        if (jsonDstPort.asInt() != dstPort) {
            description.appendText("Destination port number was " + jsonDstPort);
            return false;
        }
    }

    return true;
}