Java Code Examples for com.google.gson.JsonElement#getAsBoolean()

The following examples show how to use com.google.gson.JsonElement#getAsBoolean() . 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: JsonUtil.java    From olca-app with Mozilla Public License 2.0 10 votes vote down vote up
private static String get(JsonObject object, String... path) {
	if (path == null)
		return null;
	if (path.length == 0)
		return null;
	Stack<String> stack = new Stack<>();
	for (int i = path.length - 1; i >= 0; i--)
		stack.add(path[i]);
	while (stack.size() > 1) {
		String next = stack.pop();
		if (!object.has(next))
			return null;
		object = object.get(next).getAsJsonObject();
	}
	JsonElement value = object.get(stack.pop());
	if (value == null || value.isJsonNull())
		return null;
	if (!value.isJsonPrimitive())
		return null;
	if (value.getAsJsonPrimitive().isNumber())
		return Double.toString(value.getAsNumber().doubleValue());
	if (value.getAsJsonPrimitive().isBoolean())
		return value.getAsBoolean() ? "true" : "false";
	return value.getAsString();
}
 
Example 2
Source File: JsonLoader.java    From olca-app with Mozilla Public License 2.0 6 votes vote down vote up
private void splitExchanges(JsonObject obj) {
	JsonArray exchanges = obj.getAsJsonArray("exchanges");
	JsonArray inputs = new JsonArray();
	JsonArray outputs = new JsonArray();
	if (exchanges != null)
		for (JsonElement elem : exchanges) {
			JsonObject e = elem.getAsJsonObject();
			JsonElement isInput = e.get("input");
			if (isInput.isJsonPrimitive() && isInput.getAsBoolean())
				inputs.add(e);
			else
				outputs.add(e);
		}
	obj.remove("exchanges");
	obj.add("inputs", inputs);
	obj.add("outputs", outputs);
}
 
Example 3
Source File: Configuration.java    From supbot with MIT License 6 votes vote down vote up
/**
 * Generalized private method to get value from the saved name value pair configuration
 * @param name name
 * @param _defautlt default value
 * @return returns value from the configuration, returns _default if not found
 */
private Object GetConfig(String name, Object _defautlt){
    try {
        JsonObject jsonObject = ReadJsonObject();

        JsonElement result = jsonObject.get(name);

        if(_defautlt.getClass() == String.class)
            return result.getAsString();

        if(_defautlt.getClass() == Integer.class)
            return result.getAsInt();

        if(_defautlt.getClass() == Float.class)
            return result.getAsFloat();

        if(_defautlt.getClass() == Boolean.class)
            return result.getAsBoolean();

    } catch (IOException | NullPointerException e) {
        Log.p(e);
        //Log.e("Could not find config file or config, returning default");
    }
    return _defautlt;
}
 
Example 4
Source File: Config.java    From edx-app-android with Apache License 2.0 5 votes vote down vote up
private boolean getBoolean(String key, boolean defaultValue) {
    JsonElement element = getObject(key);
    if (element != null) {
        return element.getAsBoolean();
    } else {
        return defaultValue;
    }
}
 
Example 5
Source File: ReflexJson.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private static ReflexActionSendPlatform convertPl(JsonObject pl, JsonDeserializationContext context) {
   String evt = pl.get("m").getAsString();
   Map<String,Object> args = context.deserialize(pl.get("a"), SEND_PLATFORM_ARGS);

   JsonElement rsp = pl.get("r");
   return new ReflexActionSendPlatform(evt, args, rsp != null && rsp.getAsBoolean());
}
 
Example 6
Source File: GsonHelper.java    From goclipse with Eclipse Public License 1.0 5 votes vote down vote up
public boolean getBoolean(JsonObject jsonObject, String key) throws CommonException {
	JsonElement element = jsonObject.get(key);
	if(element != null && element.isJsonPrimitive() && element.getAsJsonPrimitive().isBoolean()) {
		return element.getAsBoolean();
	} else {
		throw wrongPropertyTypeException(key, "boolean");
	}
}
 
Example 7
Source File: DiagnosticsNode.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean getBooleanMember(String memberName, boolean defaultValue) {
  if (!json.has(memberName)) {
    return defaultValue;
  }
  final JsonElement value = json.get(memberName);
  if (value instanceof JsonNull) {
    return defaultValue;
  }
  return value.getAsBoolean();
}
 
Example 8
Source File: JsonUtils.java    From headlong with Apache License 2.0 5 votes vote down vote up
public static boolean getBoolean(JsonObject object, String key, Boolean defaultVal) {
    JsonElement element = object.get(key);
    if(element == null || element.isJsonNull()) {
        return defaultVal;
    }
    if(!element.isJsonPrimitive() || !((JsonPrimitive) element).isBoolean()) {
        throw new IllegalArgumentException(key + " is not a boolean");
    }
    return element.getAsBoolean();
}
 
Example 9
Source File: JsonHelperGson.java    From symbol-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("squid:S2447")
public Boolean getBoolean(Object object, String... path) {
    JsonElement child = getNode(convert(object, JsonObject.class), path);
    if (child == null || child.isJsonNull()) {
        return null;
    }
    if (child.isJsonObject()) {
        throw new IllegalArgumentException("Cannot extract a Boolean from an json object");
    }
    return child.getAsBoolean();
}
 
Example 10
Source File: ResultChainingIterator.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Override
public JsonElement next() {
  JsonElement jsonElement = iter.next();
  recordCount ++;
  JsonElement isDeletedElement = jsonElement.getAsJsonObject().get("IsDeleted");
  if (isDeletedElement != null && isDeletedElement.getAsBoolean()) {
    isDeletedRecordCount ++;
  }
  if (!iter.hasNext()) {
    // `jsonElement` has last record, print out total and isDeleted=true records(soft deleted) total
    log.info("====Total records: [{}] isDeleted=true records: [{}]====", recordCount, isDeletedRecordCount);
    return null;
  }
  return jsonElement;
}
 
Example 11
Source File: GsonUtilities.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
public static boolean jboolean(JsonObject object, String property) {
    if (object.has(property)) {
        JsonElement je = object.get(property);
        if (je.isJsonNull())
            return false;
        return je.getAsBoolean();
    }
    return false;
}
 
Example 12
Source File: JSONUtil.java    From org.hl7.fhir.core with Apache License 2.0 4 votes vote down vote up
public static boolean bool(JsonObject json, String name) {
  JsonElement e = json.get(name);
  return e == null || e instanceof JsonNull ? false : e.getAsBoolean();
}
 
Example 13
Source File: Element.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * A utility method to handle null values and JsonNull values.
 */
boolean getAsBoolean(String name) {
  final JsonElement element = json.get(name);
  return (element == null || element == JsonNull.INSTANCE) ? false : element.getAsBoolean();
}
 
Example 14
Source File: Element.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * A utility method to handle null values and JsonNull values.
 */
boolean getAsBoolean(String name) {
  final JsonElement element = json.get(name);
  return (element == null || element == JsonNull.INSTANCE) ? false : element.getAsBoolean();
}
 
Example 15
Source File: Preferences.java    From PYX-Reloaded with Apache License 2.0 4 votes vote down vote up
public boolean getBoolean(String key, boolean fallback) {
    JsonElement obj = get(key);
    if (obj == null) return fallback;
    else return obj.getAsBoolean();
}
 
Example 16
Source File: Account.java    From javasdk with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Deprecated
private static String parseAccountJson(String accountJson, String password) {
    JsonObject jsonObject = new JsonParser().parse(accountJson).getAsJsonObject();

    JsonElement versionStr = jsonObject.get("version");
    String version;
    if (versionStr == null) {
        version = Version.V4.getV();
    } else {
        version = versionStr.getAsString();
        if (version.equals(Version.V4.getV())) {
            return accountJson;
        }
    }

    JsonElement publicKeyStr = jsonObject.get("publicKey");
    JsonElement algoStr = jsonObject.get("algo");
    JsonElement encryptedStr = jsonObject.get("encrypted");
    JsonElement isEncrypted = jsonObject.get("privateKeyEncrypted");

    String address = jsonObject.get("address").getAsString().toLowerCase();
    String privateKeyHex;
    String publicKeyHex;
    Algo algo;

    if (algoStr == null) {
        if (isEncrypted.getAsBoolean()) {
            algo = Algo.SMDES;
        } else {
            algo = Algo.SMRAW;
        }
    } else {
        algo = Algo.getAlog(algoStr.getAsString());
    }

    if (encryptedStr == null) {
        privateKeyHex = jsonObject.get("privateKey").getAsString();
    } else {
        privateKeyHex = encryptedStr.getAsString();
    }

    privateKeyHex = privateKeyHex.toLowerCase();

    if (!algo.isSM() && publicKeyStr == null) {
        byte[] privateKey = decodePrivateKey(ByteUtil.fromHex(privateKeyHex), algo, password);
        ECKey ecKey = ECKey.fromPrivate(privateKey);
        publicKeyHex = ByteUtil.toHex(ecKey.getPubKey());
    } else {
        publicKeyHex = publicKeyStr.getAsString();
    }

    publicKeyHex = publicKeyHex.toLowerCase();

    String newAccountJson = "{\"address\":\"" + Utils.deleteHexPre(address)
            + "\",\"algo\":\"" + algo.getAlgo()
            + "\",\"privateKey\":\"" + Utils.deleteHexPre(privateKeyHex)
            + "\",\"version\":\"" + version
            + "\",\"publicKey\":\"" + Utils.deleteHexPre(publicKeyHex)
            + "\"}";


    return newAccountJson;
}
 
Example 17
Source File: SLIAuthenticationEntryPoint.java    From secure-data-service with Apache License 2.0 4 votes vote down vote up
private SLIPrincipal completeSpringAuthentication(String token) {

        // Get authentication information
        JsonObject json = restClient.sessionCheck(token);

        LOG.debug(json.toString());

        // If the user is authenticated, create an SLI principal, and authenticate
        JsonElement authElement = json.get(Constants.ATTR_AUTHENTICATED);
        if ((authElement != null) && (authElement.getAsBoolean())) {

            // Setup principal
            SLIPrincipal principal = new SLIPrincipal();
            principal.setId(token);

            // Extract user name from authentication payload
            String username = "";
            JsonElement nameElement = json.get(Constants.ATTR_AUTH_FULL_NAME);
            if (nameElement != null) {
                username = nameElement.getAsString();
                if (username != null && username.contains("@")) {
                    username = username.substring(0, username.indexOf("@"));
                    if (username.contains(".")) {
                        String first = username.substring(0, username.indexOf('.'));
                        String second = username.substring(username.indexOf('.') + 1);
                        username = first.substring(0, 1).toUpperCase()
                                + (first.length() > 1 ? first.substring(1) : "")
                                + (second.substring(0, 1).toUpperCase() + (second.length() > 1 ? second.substring(1)
                                        : ""));
                    }
                }
            } else {
                LOG.error(LOG_MESSAGE_AUTH_EXCEPTION_INVALID_NAME);
            }

            // Set principal name
            principal.setName(username);

            // Extract user roles from authentication payload
            LinkedList<GrantedAuthority> authList = new LinkedList<GrantedAuthority>();
            JsonArray grantedAuthorities = json.getAsJsonArray(Constants.ATTR_AUTH_ROLES);
            if (grantedAuthorities != null) {

                // Add authorities to user principal
                Iterator<JsonElement> authIterator = grantedAuthorities.iterator();
                while (authIterator.hasNext()) {
                    JsonElement nextElement = authIterator.next();
                    authList.add(new GrantedAuthorityImpl(nextElement.getAsString()));
                }
            } else {
                LOG.error(LOG_MESSAGE_AUTH_EXCEPTION_INVALID_ROLES);
            }
            if(json.get(Constants.ATTR_USER_TYPE).getAsString().equals(Constants.ROLE_TEACHER)) {
              authList.add(new GrantedAuthorityImpl(Constants.ROLE_EDUCATOR));
            }

            if(json.get(Constants.ATTR_ADMIN_USER).getAsBoolean()) {
             authList.add(new GrantedAuthorityImpl(Constants.ROLE_IT_ADMINISTRATOR));
            }

            SecurityContextHolder.getContext().setAuthentication(
                    new PreAuthenticatedAuthenticationToken(principal, token, authList));

            return principal;
        } else {
            LOG.error(LOG_MESSAGE_AUTH_EXCEPTION_INVALID_AUTHENTICATED);
        }

        return null;
    }
 
Example 18
Source File: JsonUtils.java    From java-debug with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Get the boolean value for the specified property from the json Object.
 * @param args
 *              the json object
 * @param property
 *              the key
 * @param defaultValue
 *              if key doesn't exist in the json object, then return the default value
 * @return the value as boolean
 */
public static boolean getBoolean(JsonObject args, String property, boolean defaultValue) {
    try {
        JsonElement obj = args.get(property);
        return obj.getAsBoolean();
    } catch (Exception e) {
        // ignore and return default value;
    }
    return defaultValue;
}
 
Example 19
Source File: InstanceRef.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * The valueAsString for String references may be truncated. If so, this property is added with
 * the value 'true'.
 *
 * New code should use 'length' and 'count' instead.
 *
 * Can return <code>null</code>.
 */
public boolean getValueAsStringIsTruncated() {
  final JsonElement elem = json.get("valueAsStringIsTruncated");
  return elem != null ? elem.getAsBoolean() : false;
}
 
Example 20
Source File: Instance.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * The valueAsString for String references may be truncated. If so, this property is added with
 * the value 'true'.
 *
 * New code should use 'length' and 'count' instead.
 *
 * Can return <code>null</code>.
 */
public boolean getValueAsStringIsTruncated() {
  final JsonElement elem = json.get("valueAsStringIsTruncated");
  return elem != null ? elem.getAsBoolean() : false;
}