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

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#isBoolean() . 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: BeatsCodec.java    From graylog-plugin-beats with GNU General Public License v3.0 6 votes vote down vote up
@Nullable
private Object valueNode(JsonNode jsonNode) {
    if (jsonNode.isInt()) {
        return jsonNode.asInt();
    } else if (jsonNode.isLong()) {
        return jsonNode.asLong();
    } else if (jsonNode.isIntegralNumber()) {
        return jsonNode.asLong();
    } else if (jsonNode.isFloatingPointNumber()) {
        return jsonNode.asDouble();
    } else if (jsonNode.isBoolean()) {
        return jsonNode.asBoolean();
    } else if (jsonNode.isNull()) {
        return null;
    } else {
        return jsonNode.asText();
    }
}
 
Example 2
Source File: Json.java    From immutables with Apache License 2.0 6 votes vote down vote up
private static Bucket parseBucket(JsonParser parser, String name, ObjectNode node)
        throws JsonProcessingException  {

  if (!node.has("key")) {
    throw new IllegalArgumentException("No 'key' attribute for " + node);
  }

  final JsonNode keyNode = node.get("key");
  final Object key;
  if (isMissingBucket(keyNode) || keyNode.isNull()) {
    key = null;
  } else if (keyNode.isTextual()) {
    key = keyNode.textValue();
  } else if (keyNode.isNumber()) {
    key = keyNode.numberValue();
  } else if (keyNode.isBoolean()) {
    key = keyNode.booleanValue();
  } else {
    // don't usually expect keys to be Objects
    key = parser.getCodec().treeToValue(node, Map.class);
  }

  return new Bucket(key, name, parseAggregations(parser, node));
}
 
Example 3
Source File: EditEntityDialog.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 6 votes vote down vote up
private Object readValue(JsonNode node) {
    if (node.isFloatingPointNumber()) {
        return node.asDouble();
    } else if (node.isNumber()) {
        return node.asLong();
    } else if (node.isBoolean()) {
        return node.asBoolean();
    } else if (node.isTextual()) {
        return node.asText();
    } else if (node.isArray()) {
        return StreamSupport.stream(node.spliterator(), false)
                .map(this::readValue)
                .collect(toList());
    }

    return node.toString();
}
 
Example 4
Source File: CustomTypeAnnotator.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
private JsonObject getValue(String key, JsonNode value){
  if(value.isTextual()){
    return annotationLookUp.get(key, value.asText());
  }
  else if(value.isBoolean()){
    return annotationLookUp.get(key, value.asBoolean());
  }
  else if(value.isDouble()){
    return annotationLookUp.get(key, value.asDouble());
  }
  else if(value.isIntegralNumber() || value.isInt()){
    return annotationLookUp.get(key, value.asInt());
  }
  else{
    return null;
  }
}
 
Example 5
Source File: JSONMatchers.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
protected static boolean describeNodeType(JsonNode item, Description desc) {
    if (item.isTextual()) {
        desc.appendText("was a text node");
    } else if (item.isNumber()) {
        desc.appendText("was a number node");
    } else if (item.isBoolean()) {
        desc.appendText("was a boolean node");
    } else if (item.isValueNode()) {
        desc.appendText("was a value node");
    } else if (item.isObject()) {
        desc.appendText("was a object node");
    } else if (item.isArray()) {
        desc.appendText("was a array node");
    } else if (item.isMissingNode()) {
        desc.appendText("was a missing node");
    } else if (item.isNull()) {
        desc.appendText("was a null node");
    }
    return false;
}
 
Example 6
Source File: ServiceParameters.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link ServiceParameters} instance based on all properties in the given object node. Only numbers, text and boolean values are added, nested object structures are ignored.
 */
public static ServiceParameters fromObjectNode(ObjectNode node) {
    ServiceParameters parameters = new ServiceParameters();

    Iterator<String> ir = node.fieldNames();
    String name = null;
    JsonNode value = null;
    while (ir.hasNext()) {
        name = ir.next();
        value = node.get(name);

        // Depending on the type, extract the raw value object
        if (value != null) {
            if (value.isNumber()) {
                parameters.addParameter(name, value.numberValue());
            } else if (value.isBoolean()) {
                parameters.addParameter(name, value.booleanValue());
            } else if (value.isTextual()) {
                parameters.addParameter(name, value.textValue());
            }
        }
    }
    return parameters;
}
 
Example 7
Source File: WorkflowParser.java    From cwlexec with Apache License 2.0 6 votes vote down vote up
private static Object toDefaultValue(String descTop,
        String id,
        JsonNode defaultNode) throws CWLException {
    Object value = null;
    if (defaultNode != null) {
        if (defaultNode.isTextual()) {
            value = defaultNode.asText();
        } else if (defaultNode.isInt()) {
            value = Integer.valueOf(defaultNode.asInt());
        } else if (defaultNode.isLong()) {
            value = Long.valueOf(defaultNode.asLong());
        } else if (defaultNode.isFloat()) {
            value = Float.valueOf(defaultNode.floatValue());
        } else if (defaultNode.isDouble()) {
            value = Double.valueOf(defaultNode.asDouble());
        } else if (defaultNode.isBoolean()) {
            value = Boolean.valueOf(defaultNode.asBoolean());
        } else if (defaultNode.isArray()) {
            value = toDefaultArrayValue(descTop, id, defaultNode);
        } else if (defaultNode.isObject()) {
            value = toDefaultObjectValue(descTop, id, defaultNode);
        }
    }
    return value;
}
 
Example 8
Source File: JSONMatchers.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean matchesSafely(JsonNode item, Description desc) {
    if (item.isBoolean()) {
        return true;
    } else {
        return describeNodeType(item, desc);
    }
}
 
Example 9
Source File: GeneralUtils.java    From template-compiler with Apache License 2.0 5 votes vote down vote up
/**
 * Determines the boolean value of a node based on its type.
 */
public static boolean isTruthy(JsonNode node) {
  if (node.isTextual()) {
    return !node.asText().equals("");
  }
  if (node.isNumber() || node.isBoolean()) {
    return node.asLong() != 0;
  }
  if (node.isMissingNode() || node.isNull()) {
    return false;
  }
  return node.size() != 0;
}
 
Example 10
Source File: JsonWrittenEventProvider.java    From tasmo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isDeletion() {
    JsonNode deletion = instanceNode.get(ReservedFields.DELETED);
    if (deletion != null && deletion.isBoolean()) {
        return deletion.booleanValue();
    }

    return false;
}
 
Example 11
Source File: JSONConfigParser.java    From walkmod-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Map<String, Object> getParams(JsonNode next) {
	if (next.has("params")) {
		Iterator<Entry<String, JsonNode>> it2 = next.get("params").fields();
		Map<String, Object> params = new HashMap<String, Object>();
		while (it2.hasNext()) {
			Entry<String, JsonNode> param = it2.next();
			JsonNode value = param.getValue();
			if (value.isTextual()) {
				params.put(param.getKey(), value.asText());
			} else if (value.isInt()) {
				params.put(param.getKey(), value.asInt());
			} else if (value.isBoolean()) {
				params.put(param.getKey(), value.asBoolean());
			} else if (value.isDouble() || value.isFloat() || value.isBigDecimal()) {
				params.put(param.getKey(), value.asDouble());
			} else if (value.isLong() || value.isBigInteger()) {
				params.put(param.getKey(), value.asLong());
			} else {
				params.put(param.getKey(), value);
			}
			params.put(param.getKey(), param.getValue().asText());
		}
		return params;

	}
	return null;
}
 
Example 12
Source File: OpenAPIDeserializer.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
public String inferTypeFromArray(ArrayNode an) {
    if(an.size() == 0) {
        return "string";
    }
    String type = null;
    for(int i = 0; i < an.size(); i++) {
        JsonNode element = an.get(0);
        if(element.isBoolean()) {
            if(type == null) {
                type = "boolean";
            }
            else if(!"boolean".equals(type)) {
                type = "string";
            }
        }
        else if(element.isNumber()) {
            if(type == null) {
                type = "number";
            }
            else if(!"number".equals(type)) {
                type = "string";
            }
        }
        else {
            type = "string";
        }
    }

    return type;
}
 
Example 13
Source File: PrimitiveTypeProvider.java    From cineast with MIT License 5 votes vote down vote up
public static PrimitiveTypeProvider fromJSON(JsonNode json) {
  if (json == null) {
    return NothingProvider.INSTANCE;
  }

  if (json.isTextual()) {
    return new StringTypeProvider(json.asText());
  }

  if (json.isInt()) {
    return new IntTypeProvider(json.asInt());
  }

  if (json.isLong()) {
    return new LongTypeProvider(json.asLong());
  }

  if (json.isFloat()) {
    return new FloatTypeProvider(json.floatValue());
  }

  if (json.isDouble()) {
    return new DoubleTypeProvider(json.doubleValue());
  }

  if (json.isBoolean()) {
    return new BooleanTypeProvider(json.asBoolean());
  }

  // TODO are arrays relevant here?
  return NothingProvider.INSTANCE;
}
 
Example 14
Source File: SerializableConverter.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private Serializable serializableNodeValue(JsonNode node) {
  if (node.isNumber()) {
    return node.numberValue();
  } else if (node.isBoolean()) {
    return node.booleanValue();
  } else if (node.isTextual()) {
    return node.textValue();
  } else {
    throw new RuntimeException("Unable to deserialize preference value:" + node.asText());
  }
}
 
Example 15
Source File: Schema.java    From styx with Apache License 2.0 4 votes vote down vote up
@Override
public void validate(List<String> parents, JsonNode parent, JsonNode value, Function<String, FieldType> typeExtensions) {
    if (!value.isBoolean() && !canParseAsBoolean(value)) {
        throw new SchemaValidationException(message(parents, describe(), value));
    }
}
 
Example 16
Source File: ODataJsonDeserializer.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
private boolean matchBooleanCase(final JsonNode node, final EdmPrimitiveTypeKind primKind) {
  return node.isBoolean() && primKind == EdmPrimitiveTypeKind.Boolean;
}
 
Example 17
Source File: JsonQLDataSource.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected Object getConvertedValue(JRJsonNode node, JRField jrField) throws JRException {
    JsonNode dataNode = node.getDataNode();
    Class<?> valueClass = jrField.getValueClass();

    if (log.isDebugEnabled()) {
        log.debug("attempting to convert: " + dataNode + " to class: " + valueClass);
    }

    if (Object.class.equals(valueClass)) {
        return dataNode;
    }

    Object result = null;

    if (!dataNode.isNull())  {
        try {
            if (Boolean.class.equals(valueClass) && dataNode.isBoolean()) {
                result = dataNode.booleanValue();

            } else if (BigDecimal.class.equals(valueClass) && dataNode.isBigDecimal()) {
                result = dataNode.decimalValue();

            } else if (BigInteger.class.equals(valueClass) && dataNode.isBigInteger()) {
                result = dataNode.bigIntegerValue();

            } else if (Double.class.equals(valueClass) && dataNode.isDouble()) {
                result = dataNode.doubleValue();

            } else if (Integer.class.equals(valueClass) && dataNode.isInt()) {
                result = dataNode.intValue();

            } else if (Number.class.isAssignableFrom(valueClass) && dataNode.isNumber()) {
                result = convertNumber(dataNode.numberValue(), valueClass);

            } else {
                result = convertStringValue(dataNode.asText(), valueClass);
            }

            if (result == null) {
                throw new JRException(EXCEPTION_MESSAGE_KEY_CANNOT_CONVERT_FIELD_TYPE,
                        new Object[]{jrField.getName(), valueClass.getName()});
            }

        } catch (Exception e) {
            throw new JRException(EXCEPTION_MESSAGE_KEY_JSON_FIELD_VALUE_NOT_RETRIEVED,
                    new Object[]{jrField.getName(), valueClass.getName()}, e);
        }
    }

    return result;
}
 
Example 18
Source File: JsonUtil.java    From kite with Apache License 2.0 4 votes vote down vote up
private static boolean matches(JsonNode datum, Schema schema) {
  switch (schema.getType()) {
    case RECORD:
      if (datum.isObject()) {
        // check that each field is present or has a default
        boolean missingField = false;
        for (Schema.Field field : schema.getFields()) {
          if (!datum.has(field.name()) && field.defaultValue() == null) {
            missingField = true;
            break;
          }
        }
        if (!missingField) {
          return true;
        }
      }
      break;
    case UNION:
      if (resolveUnion(datum, schema.getTypes()) != null) {
        return true;
      }
      break;
    case MAP:
      if (datum.isObject()) {
        return true;
      }
      break;
    case ARRAY:
      if (datum.isArray()) {
        return true;
      }
      break;
    case BOOLEAN:
      if (datum.isBoolean()) {
        return true;
      }
      break;
    case FLOAT:
      if (datum.isFloat() || datum.isInt()) {
        return true;
      }
      break;
    case DOUBLE:
      if (datum.isDouble() || datum.isFloat() ||
          datum.isLong() || datum.isInt()) {
        return true;
      }
      break;
    case INT:
      if (datum.isInt()) {
        return true;
      }
      break;
    case LONG:
      if (datum.isLong() || datum.isInt()) {
        return true;
      }
      break;
    case STRING:
      if (datum.isTextual()) {
        return true;
      }
      break;
    case ENUM:
      if (datum.isTextual() && schema.hasEnumSymbol(datum.textValue())) {
        return true;
      }
      break;
    case BYTES:
    case FIXED:
      if (datum.isBinary()) {
        return true;
      }
      break;
    case NULL:
      if (datum == null || datum.isNull()) {
        return true;
      }
      break;
    default: // UNION or unknown
      throw new IllegalArgumentException("Unsupported schema: " + schema);
  }
  return false;
}
 
Example 19
Source File: CoinbaseTransfer.java    From zheshiyigeniubidexiangmu with MIT License 4 votes vote down vote up
@Override
public CoinbaseTransfer deserialize(JsonParser jp, DeserializationContext ctxt)
    throws IOException, JsonProcessingException {

  final ObjectCodec oc = jp.getCodec();
  final JsonNode node = oc.readTree(jp);

  final JsonNode successNode = node.path("success");
  boolean success = true;
  final List<String> errors = new ArrayList<>();
  if (successNode.isBoolean()) {
    success = successNode.asBoolean();
    final JsonNode errorsNode = node.path("errors");
    if (errorsNode.isArray())
      for (JsonNode errorNode : errorsNode) errors.add(errorNode.asText());
  }

  final JsonNode transferNode = node.path("transfer");
  final String id = transferNode.path("id").asText();
  final String fundingType = transferNode.path("_type").asText();
  final CoinbaseTransferType type =
      CoinbaseTransferType.valueOf(transferNode.path("type").asText().toUpperCase());
  final String code = transferNode.path("code").asText();
  final Date createdAt =
      DateUtils.fromISO8601DateString(transferNode.path("created_at").asText());
  final JsonNode feesNode = transferNode.path("fees");
  final CoinbaseMoney coinbaseFee =
      CoinbaseCentsDeserializer.getCoinbaseMoneyFromCents(feesNode.path("coinbase"));
  final CoinbaseMoney bankFee =
      CoinbaseCentsDeserializer.getCoinbaseMoneyFromCents(feesNode.path("bank"));
  final Date payoutDate =
      DateUtils.fromISO8601DateString(transferNode.path("payout_date").asText());
  final String transactionId = transferNode.path("transaction_id").asText();
  final CoinbaseTransferStatus status =
      CoinbaseTransferStatus.valueOf(transferNode.path("status").asText().toUpperCase());
  final CoinbaseMoney btcAmount =
      CoinbaseMoneyDeserializer.getCoinbaseMoneyFromNode(transferNode.path("btc"));
  final CoinbaseMoney subtotal =
      CoinbaseMoneyDeserializer.getCoinbaseMoneyFromNode(transferNode.path("subtotal"));
  final CoinbaseMoney total =
      CoinbaseMoneyDeserializer.getCoinbaseMoneyFromNode(transferNode.path("total"));
  final String description = transferNode.path("description").asText();

  return new CoinbaseTransfer(
      id,
      type,
      fundingType,
      code,
      createdAt,
      coinbaseFee,
      bankFee,
      payoutDate,
      transactionId,
      status,
      btcAmount,
      subtotal,
      total,
      description,
      success,
      errors);
}
 
Example 20
Source File: RestDMLServiceImpl.java    From sql-layer with GNU Affero General Public License v3.0 4 votes vote down vote up
protected void callDefaultProcedure(PrintWriter writer, HttpServletRequest request, String jsonpArgName,
                                    JDBCCallableStatement call, Map<String,List<String>> queryParams, String jsonParams) throws SQLException {
    if (queryParams != null) {
        for (Map.Entry<String,List<String>> entry : queryParams.entrySet()) {
            if (jsonpArgName.equals(entry.getKey()))
                continue;
            if (entry.getValue().size() != 1)
                throw new WrongExpressionArityException(1, entry.getValue().size());
            call.setString(entry.getKey(), entry.getValue().get(0));
        }
    }
    if (jsonParams != null) {
        JsonNode parsed;
        try {
            parsed = jsonParser(jsonParams).readValueAsTree();
        }
        catch (IOException ex) {
            throw new AkibanInternalException("Error reading from string", ex);
        }
        if (parsed.isObject()) {
            Iterator<String> iter = parsed.fieldNames();
            while (iter.hasNext()) {
                String field = iter.next();
                JsonNode value = parsed.get(field);
                if (value.isBigDecimal()) {
                    call.setBigDecimal(field, value.decimalValue());
                }
                else if (value.isBoolean()) {
                    call.setBoolean(field, value.asBoolean());
                }
                else if (value.isDouble()) {
                    call.setDouble(field, value.asDouble());
                }
                else if (value.isInt()) {
                    call.setInt(field, value.asInt());
                }
                else if (value.isLong()) {
                    call.setLong(field, value.asLong());
                }
                else {
                    call.setString(field, value.textValue());
                }
            }
        }
        else {
            throw new InvalidArgumentTypeException("JSON must be object or array");
        }
    }
    boolean results = call.execute();
    AkibanAppender appender = AkibanAppender.of(writer);
    appender.append('{');
    boolean first = true;
    JDBCParameterMetaData md = (JDBCParameterMetaData)call.getParameterMetaData();
    for (int i = 1; i <= md.getParameterCount(); i++) {
        String name;
        switch (md.getParameterMode(i)) {
        case ParameterMetaData.parameterModeOut:
        case ParameterMetaData.parameterModeInOut:
            name = md.getParameterName(i);
            if (name == null)
                name = String.format("arg%d", i);
            if (first)
                first = false;
            else
                appender.append(',');
            appender.append('"');
            Quote.DOUBLE_QUOTE.append(appender, name);
            appender.append("\":");
            call.formatAsJson(i, appender, options);
            break;
        }
    }
    int nresults = 0;
    while(results) {
        beginResultSetArray(appender, first, nresults++);
        first = false;
        collectResults((JDBCResultSet) call.getResultSet(), appender, options);
        endResultSetArray(appender);
        results = call.getMoreResults();
    }
    appender.append('}');
}