Java Code Examples for com.google.gson.JsonPrimitive#isBoolean()

The following examples show how to use com.google.gson.JsonPrimitive#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: RemoteValidationServlet.java    From dolphin-platform with Apache License 2.0 6 votes vote down vote up
private Set<ConstraintViolation<?>> validate(final String typeName, final String propertyName, final JsonElement propertyElement) {
    Assert.requireNonNull(propertyElement, "propertyElement");
    if (!propertyElement.isJsonPrimitive() && !propertyElement.isJsonNull()) {
        throw new IllegalArgumentException("Only primitive or null properties supported. Wrong type for " + typeName + "." + propertyName);
    }
    if (propertyElement.isJsonNull()) {
        return remoteValidator.validateValue(typeName, propertyName, null);
    }
    final JsonPrimitive primitiveValue = propertyElement.getAsJsonPrimitive();
    if (primitiveValue.isBoolean()) {
        return remoteValidator.validateValue(typeName, propertyName, primitiveValue.getAsBoolean());
    } else if (primitiveValue.isNumber()) {
        return remoteValidator.validateValue(typeName, propertyName, primitiveValue.getAsNumber());
    } else if (primitiveValue.isString()) {
        return remoteValidator.validateValue(typeName, propertyName, primitiveValue.getAsString());
    }
    throw new IllegalArgumentException("Not supported type for " + typeName + "." + propertyName);
}
 
Example 2
Source File: MapTypeAdapterFactory.java    From letv with Apache License 2.0 6 votes vote down vote up
private String keyToString(JsonElement keyElement) {
    if (keyElement.isJsonPrimitive()) {
        JsonPrimitive primitive = keyElement.getAsJsonPrimitive();
        if (primitive.isNumber()) {
            return String.valueOf(primitive.getAsNumber());
        }
        if (primitive.isBoolean()) {
            return Boolean.toString(primitive.getAsBoolean());
        }
        if (primitive.isString()) {
            return primitive.getAsString();
        }
        throw new AssertionError();
    } else if (keyElement.isJsonNull()) {
        return "null";
    } else {
        throw new AssertionError();
    }
}
 
Example 3
Source File: MapTypeAdapterFactory.java    From gson with Apache License 2.0 6 votes vote down vote up
private String keyToString(JsonElement keyElement) {
  if (keyElement.isJsonPrimitive()) {
    JsonPrimitive primitive = keyElement.getAsJsonPrimitive();
    if (primitive.isNumber()) {
      return String.valueOf(primitive.getAsNumber());
    } else if (primitive.isBoolean()) {
      return Boolean.toString(primitive.getAsBoolean());
    } else if (primitive.isString()) {
      return primitive.getAsString();
    } else {
      throw new AssertionError();
    }
  } else if (keyElement.isJsonNull()) {
    return "null";
  } else {
    throw new AssertionError();
  }
}
 
Example 4
Source File: MapTypeAdapterFactory.java    From framework with GNU Affero General Public License v3.0 6 votes vote down vote up
private String keyToString(JsonElement keyElement) {
  if (keyElement.isJsonPrimitive()) {
    JsonPrimitive primitive = keyElement.getAsJsonPrimitive();
    if (primitive.isNumber()) {
      return String.valueOf(primitive.getAsNumber());
    } else if (primitive.isBoolean()) {
      return Boolean.toString(primitive.getAsBoolean());
    } else if (primitive.isString()) {
      return primitive.getAsString();
    } else {
      throw new AssertionError();
    }
  } else if (keyElement.isJsonNull()) {
    return "null";
  } else {
    throw new AssertionError();
  }
}
 
Example 5
Source File: GsonUtils.java    From soul with Apache License 2.0 6 votes vote down vote up
/**
 * Get JsonElement class type.
 *
 * @param element the element
 * @return Class class
 */
public Class getType(final JsonElement element) {
    if (!element.isJsonPrimitive()) {
        return element.getClass();
    }
    
    final JsonPrimitive primitive = element.getAsJsonPrimitive();
    if (primitive.isString()) {
        return String.class;
    } else if (primitive.isNumber()) {
        String numStr = primitive.getAsString();
        if (numStr.contains(DOT) || numStr.contains(E)
                || numStr.contains("E")) {
            return Double.class;
        }
        return Long.class;
    } else if (primitive.isBoolean()) {
        return Boolean.class;
    } else {
        return element.getClass();
    }
}
 
Example 6
Source File: JSONRequestParser.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a given <code>{@link JsonElement}</code> to a <code>String</code> DataType
 * Predicted based on XACML 3.0 JSON profile
 *
 * @param element
 * @return
 */
private static String jsonElementToDataType(JsonPrimitive element) {
    if (element.isString()) {
        return EntitlementEndpointConstants.ATTRIBUTE_DATA_TYPE_STRING;
    } else if (element.isBoolean()) {
        return EntitlementEndpointConstants.ATTRIBUTE_DATA_TYPE_BOOLEAN;
    } else if (element.isNumber()) {
        double n1 = element.getAsDouble();
        int n2 = element.getAsInt();
        if (Math.ceil(n1) == n2) {
            return EntitlementEndpointConstants.ATTRIBUTE_DATA_TYPE_INTEGER;
        } else {
            return EntitlementEndpointConstants.ATTRIBUTE_DATA_TYPE_DOUBLE;
        }
    }

    return null;
}
 
Example 7
Source File: MainView.java    From HiJson with Apache License 2.0 6 votes vote down vote up
private void formatJsonPrimitive(String key, JsonPrimitive pri, DefaultMutableTreeNode pNode) {
    if(pri.isJsonNull()){
        pNode.add(Kit.nullNode(key));
    }else if (pri.isNumber()) {
        pNode.add(Kit.numNode(key ,pri.getAsString()));
    }else if (pri.isBoolean()) {
        pNode.add(Kit.boolNode(key,pri.getAsBoolean()));
    }else if (pri.isString()) {
        pNode.add(Kit.strNode(key, pri.getAsString()));
    }else if(pri.isJsonArray()){
        createJsonArray(pri.getAsJsonArray(),pNode,key);
    }else if(pri.isJsonObject()){
            JsonObject child = pri.getAsJsonObject();
            DefaultMutableTreeNode node = Kit.objNode(key);
            createJsonObject(child,node);
            pNode.add(node);
    }else if(pri.isJsonPrimitive()){
        formatJsonPrimitive(key,pri.getAsJsonPrimitive(),pNode);
    }
}
 
Example 8
Source File: ValueEncoder.java    From dolphin-platform with Apache License 2.0 6 votes vote down vote up
public static Object decodeValue(final JsonElement jsonElement) {
    if (jsonElement == null || jsonElement.isJsonNull()) {
        return null;
    }
    if (! jsonElement.isJsonPrimitive()) {
        throw new JsonParseException("Illegal JSON detected");
    }
    final JsonPrimitive value = (JsonPrimitive) jsonElement;

    if (value.isString()) {
        return value.getAsString();
    } else if (value.isBoolean()) {
        return value.getAsBoolean();
    } else if (value.isNumber()) {
        return value.getAsNumber();
    }
    throw new JsonParseException("Currently only String, Boolean, or Number are allowed as primitives");
}
 
Example 9
Source File: GsonObjectDeserializer.java    From qaf with MIT License 5 votes vote down vote up
public static Object read(JsonElement in) {

		if (in.isJsonArray()) {
			List<Object> list = new ArrayList<Object>();
			JsonArray arr = in.getAsJsonArray();
			for (JsonElement anArr : arr) {
				list.add(read(anArr));
			}
			return list;
		} else if (in.isJsonObject()) {
			Map<String, Object> map = new LinkedTreeMap<String, Object>();
			JsonObject obj = in.getAsJsonObject();
			Set<Map.Entry<String, JsonElement>> entitySet = obj.entrySet();
			for (Map.Entry<String, JsonElement> entry : entitySet) {
				map.put(entry.getKey(), read(entry.getValue()));
			}
			return map;
		} else if (in.isJsonPrimitive()) {
			JsonPrimitive prim = in.getAsJsonPrimitive();
			if (prim.isBoolean()) {
				return prim.getAsBoolean();
			} else if (prim.isString()) {
				return prim.getAsString();
			} else if (prim.isNumber()) {
				if (prim.getAsString().contains("."))
					return prim.getAsDouble();
				else {
					return prim.getAsLong();
				}
			}
		}
		return null;
	}
 
Example 10
Source File: XGsonBuilder.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Boolean extractBoolean(JsonElement jsonElement, String name) {
	if ((null != jsonElement) && jsonElement.isJsonObject() && StringUtils.isNotEmpty(name)) {
		JsonElement element = extract(jsonElement, name);
		if (null != element && element.isJsonPrimitive()) {
			JsonPrimitive jsonPrimitive = element.getAsJsonPrimitive();
			if (jsonPrimitive.isBoolean())
				return jsonPrimitive.getAsBoolean();
		}
	}
	return null;
}
 
Example 11
Source File: JsonValueExtractor.java    From json-logic-java with MIT License 5 votes vote down vote up
public static Object extract(JsonElement element) {
  if (element.isJsonObject()) {
    Map<String, Object> map = new HashMap<>();
    JsonObject object = element.getAsJsonObject();

    for (String key : object.keySet()) {
      map.put(key, extract(object.get(key)));
    }

    return map;
  }
  else if (element.isJsonArray()) {
    List<Object> values = new ArrayList<>();

    for (JsonElement item : element.getAsJsonArray()) {
      values.add(extract(item));
    }

    return values;
  }
  else if (element.isJsonNull()) {
    return null;
  }
  else if (element.isJsonPrimitive()) {
    JsonPrimitive primitive = element.getAsJsonPrimitive();

    if (primitive.isBoolean()) {
      return primitive.getAsBoolean();
    }
    else if (primitive.isNumber()) {
      return primitive.getAsNumber().doubleValue();
    }
    else {
      return primitive.getAsString();
    }
  }

  return element.toString();
}
 
Example 12
Source File: JsonUtil.java    From java-trader with Apache License 2.0 5 votes vote down vote up
public static Object json2value(JsonElement json) {
    Object result = null;
    if ( json.isJsonNull() ) {
        result = null;
    }else if ( json.isJsonObject() ) {
        JsonObject json0 = (JsonObject)json;
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        for(String key:json0.keySet()) {
            map.put(key, json2value(json0.get(key)));
        }
        result = map;
    }else if ( json.isJsonArray() ) {
        JsonArray arr = (JsonArray)json;
        ArrayList<Object> list = new ArrayList<>(arr.size());
        for(int i=0;i<arr.size();i++) {
            list.add(json2value(arr.get(i)));
        }
        result = list;
    } else if ( json.isJsonPrimitive() ) {
        JsonPrimitive p = (JsonPrimitive)json;
        if ( p.isBoolean() ) {
            result = p.getAsBoolean();
        }else if ( p.isNumber() ) {
            result = p.getAsDouble();
        }else if ( p.isString()) {
            result = p.getAsString();
        }else {
            result = p.getAsString();
        }
    }
    return result;
}
 
Example 13
Source File: CheckboxSetting.java    From ForgeWurst with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void fromJson(JsonElement json)
{
	if(!json.isJsonPrimitive())
		return;
	
	JsonPrimitive primitive = json.getAsJsonPrimitive();
	if(!primitive.isBoolean())
		return;
	
	setChecked(primitive.getAsBoolean());
}
 
Example 14
Source File: JsonParser.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private void parseChildPrimitiveInstance(Element context, Property property, String name, String npath,
   JsonElement main, JsonElement fork) throws FHIRFormatError, DefinitionException {
	if (main != null && !(main instanceof JsonPrimitive))
		logError(line(main), col(main), npath, IssueType.INVALID, "This property must be an simple value, not a "+main.getClass().getName(), IssueSeverity.ERROR);
	else if (fork != null && !(fork instanceof JsonObject))
		logError(line(fork), col(fork), npath, IssueType.INVALID, "This property must be an object, not a "+fork.getClass().getName(), IssueSeverity.ERROR);
	else {
		Element n = new Element(name, property).markLocation(line(main != null ? main : fork), col(main != null ? main : fork));
		context.getChildren().add(n);
		if (main != null) {
			JsonPrimitive p = (JsonPrimitive) main;
			n.setValue(p.getAsString());
			if (!n.getProperty().isChoice() && n.getType().equals("xhtml")) {
				try {
        	  n.setXhtml(new XhtmlParser().setValidatorMode(policy == ValidationPolicy.EVERYTHING).parse(n.getValue(), null).getDocumentElement());
				} catch (Exception e) {
					logError(line(main), col(main), npath, IssueType.INVALID, "Error parsing XHTML: "+e.getMessage(), IssueSeverity.ERROR);
				}
			}
			if (policy == ValidationPolicy.EVERYTHING) {
				// now we cross-check the primitive format against the stated type
				if (Utilities.existsInList(n.getType(), "boolean")) {
					if (!p.isBoolean())
						logError(line(main), col(main), npath, IssueType.INVALID, "Error parsing JSON: the primitive value must be a boolean", IssueSeverity.ERROR);
				} else if (Utilities.existsInList(n.getType(), "integer", "unsignedInt", "positiveInt", "decimal")) {
					if (!p.isNumber())
						logError(line(main), col(main), npath, IssueType.INVALID, "Error parsing JSON: the primitive value must be a number", IssueSeverity.ERROR);
				} else if (!p.isString())
		  logError(line(main), col(main), npath, IssueType.INVALID, "Error parsing JSON: the primitive value must be a string", IssueSeverity.ERROR);
			}
		}
		if (fork != null) {
			JsonObject child = (JsonObject) fork;
			checkObject(child, npath);
			parseChildren(npath, child, n, false);
		}
	}
}
 
Example 15
Source File: HolderJsonSerializer.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Override
public Holder deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
  JsonObject root = (JsonObject) json;

  ImmutableHolder.Builder builder = ImmutableHolder.builder();

  if (root.has("id")) {
    builder.id(root.get("id").getAsString());
  }

  JsonElement value = root.get(VALUE_PROPERTY);
  if (value == null) {
    throw new JsonParseException(String.format("%s not found for %s in JSON", VALUE_PROPERTY, type));
  }

  if (value.isJsonObject()) {
    final String valueTypeName = value.getAsJsonObject().get(Holder.TYPE_PROPERTY).getAsString();
    try {
      Class<?> valueType = Class.forName(valueTypeName);
      builder.value(context.deserialize(value, valueType));
    } catch (ClassNotFoundException e) {
      throw new JsonParseException(String.format("Couldn't construct value class %s for %s", valueTypeName, type), e);
    }
  } else if (value.isJsonPrimitive()) {
    final JsonPrimitive primitive = value.getAsJsonPrimitive();
    if (primitive.isString()) {
      builder.value(primitive.getAsString());
    } else if (primitive.isNumber()) {
      builder.value(primitive.getAsInt());
    } else if (primitive.isBoolean()) {
      builder.value(primitive.getAsBoolean());
    }
  } else {
    throw new JsonParseException(
        String.format("Couldn't deserialize %s : %s. Not a primitive or object", VALUE_PROPERTY, value));
  }

  return builder.build();

}
 
Example 16
Source File: GsonDeserializerObjectWrapper.java    From qaf with MIT License 4 votes vote down vote up
private Object read(JsonElement in, Type typeOfT) {
	
	if (in.isJsonArray()) {
		JsonArray arr = in.getAsJsonArray();

		boolean isArray = isArray(typeOfT);
		Collection<Object> list = isArray ? new ArrayList<Object>()
				: context.deserialize(new JsonArray(0), typeOfT);
		for (JsonElement anArr : arr) {
			((Collection<Object>) list).add(read(anArr, getTypeArguments(typeOfT, 0)));
		}
		if (isArray) {
			return toArray((List<Object>) list);
		}
		try {
			return ClassUtil.getClass(typeOfT).cast(list);
		} catch (Exception e) {
			return context.deserialize(in, typeOfT);
		}
	} else if (in.isJsonObject()
			&& (isAssignableFrom(typeOfT, Map.class) || ClassUtil.getClass(typeOfT).equals(Object.class))) {
		Map<Object, Object> map = context.deserialize(new JsonObject(), typeOfT);//new LinkedTreeMap<Object, Object>();
		JsonObject obj = in.getAsJsonObject();
		Set<Map.Entry<String, JsonElement>> entitySet = obj.entrySet();
		for (Map.Entry<String, JsonElement> entry : entitySet) {
			map.put(entry.getKey(), read(entry.getValue(), getTypeArguments(typeOfT, 1)));
		}
		return map;
	} else if (in.isJsonPrimitive() && ClassUtil.getClass(typeOfT).equals(Object.class)) {
		JsonPrimitive prim = in.getAsJsonPrimitive();
		if (prim.isBoolean()) {
			return prim.getAsBoolean();
		} else if (prim.isString()) {
			return prim.getAsString();
		} else if (prim.isNumber()) {
			if (prim.getAsString().contains("."))
				return prim.getAsDouble();
			else {
				return prim.getAsLong();
			}
		}
	}
	return context.deserialize(in, typeOfT);
}
 
Example 17
Source File: DataUtil.java    From Prism with MIT License 4 votes vote down vote up
/**
 * Attempts to convert a JsonElement to an a known type.
 *
 * @param element JsonElement
 * @return Optional<Object>
 */
private static Optional<Object> jsonElementToObject(JsonElement element) {
    if (element.isJsonArray()) {
        List<Object> list = Lists.newArrayList();
        JsonArray jsonArray = element.getAsJsonArray();
        jsonArray.forEach(entry -> jsonElementToObject(entry).ifPresent(list::add));
        return Optional.of(list);
    } else if (element.isJsonObject()) {
        JsonObject jsonObject = element.getAsJsonObject();
        PrimitiveArray primitiveArray = PrimitiveArray.of(jsonObject);
        if (primitiveArray != null) {
            return Optional.of(primitiveArray.getArray());
        }

        return Optional.of(dataViewFromJson(jsonObject));
    } else if (element.isJsonPrimitive()) {
        JsonPrimitive jsonPrimitive = element.getAsJsonPrimitive();
        if (jsonPrimitive.isBoolean()) {
            return Optional.of(jsonPrimitive.getAsBoolean());
        } else if (jsonPrimitive.isNumber()) {
            Number number = NumberUtils.createNumber(jsonPrimitive.getAsString());
            if (number instanceof Byte) {
                return Optional.of(number.byteValue());
            } else if (number instanceof Double) {
                return Optional.of(number.doubleValue());
            } else if (number instanceof Float) {
                return Optional.of(number.floatValue());
            } else if (number instanceof Integer) {
                return Optional.of(number.intValue());
            } else if (number instanceof Long) {
                return Optional.of(number.longValue());
            } else if (number instanceof Short) {
                return Optional.of(number.shortValue());
            }
        } else if (jsonPrimitive.isString()) {
            return Optional.of(jsonPrimitive.getAsString());
        }
    }

    return Optional.empty();
}
 
Example 18
Source File: JsonTreeReader.java    From gson with Apache License 2.0 4 votes vote down vote up
@Override public JsonToken peek() throws IOException {
  if (stackSize == 0) {
    return JsonToken.END_DOCUMENT;
  }

  Object o = peekStack();
  if (o instanceof Iterator) {
    boolean isObject = stack[stackSize - 2] instanceof JsonObject;
    Iterator<?> iterator = (Iterator<?>) o;
    if (iterator.hasNext()) {
      if (isObject) {
        return JsonToken.NAME;
      } else {
        push(iterator.next());
        return peek();
      }
    } else {
      return isObject ? JsonToken.END_OBJECT : JsonToken.END_ARRAY;
    }
  } else if (o instanceof JsonObject) {
    return JsonToken.BEGIN_OBJECT;
  } else if (o instanceof JsonArray) {
    return JsonToken.BEGIN_ARRAY;
  } else if (o instanceof JsonPrimitive) {
    JsonPrimitive primitive = (JsonPrimitive) o;
    if (primitive.isString()) {
      return JsonToken.STRING;
    } else if (primitive.isBoolean()) {
      return JsonToken.BOOLEAN;
    } else if (primitive.isNumber()) {
      return JsonToken.NUMBER;
    } else {
      throw new AssertionError();
    }
  } else if (o instanceof JsonNull) {
    return JsonToken.NULL;
  } else if (o == SENTINEL_CLOSED) {
    throw new IllegalStateException("JsonReader is closed");
  } else {
    throw new AssertionError();
  }
}
 
Example 19
Source File: JsonTreeReader.java    From framework with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override public JsonToken peek() throws IOException {
  if (stack.isEmpty()) {
    return JsonToken.END_DOCUMENT;
  }

  Object o = peekStack();
  if (o instanceof Iterator) {
    boolean isObject = stack.get(stack.size() - 2) instanceof JsonObject;
    Iterator<?> iterator = (Iterator<?>) o;
    if (iterator.hasNext()) {
      if (isObject) {
        return JsonToken.NAME;
      } else {
        stack.add(iterator.next());
        return peek();
      }
    } else {
      return isObject ? JsonToken.END_OBJECT : JsonToken.END_ARRAY;
    }
  } else if (o instanceof JsonObject) {
    return JsonToken.BEGIN_OBJECT;
  } else if (o instanceof JsonArray) {
    return JsonToken.BEGIN_ARRAY;
  } else if (o instanceof JsonPrimitive) {
    JsonPrimitive primitive = (JsonPrimitive) o;
    if (primitive.isString()) {
      return JsonToken.STRING;
    } else if (primitive.isBoolean()) {
      return JsonToken.BOOLEAN;
    } else if (primitive.isNumber()) {
      return JsonToken.NUMBER;
    } else {
      throw new AssertionError();
    }
  } else if (o instanceof JsonNull) {
    return JsonToken.NULL;
  } else if (o == SENTINEL_CLOSED) {
    throw new IllegalStateException("JsonReader is closed");
  } else {
    throw new AssertionError();
  }
}
 
Example 20
Source File: BetterJsonObject.java    From Hyperium with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * The optional boolean method, returns the default value if
 * the key is null, empty or the data does not contain
 * the key. This will also return the default value if
 * the data value is not a boolean
 *
 * @param key the key the value will be loaded from
 * @return the value in the json data set or the default if the key cannot be found
 */
public boolean optBoolean(String key, boolean value) {
    if (key == null || key.isEmpty() || !has(key)) return value;
    JsonPrimitive primitive = asPrimitive(get(key));
    return primitive != null && primitive.isBoolean() ? primitive.getAsBoolean() : value;
}