List of usage examples for com.google.gson JsonElement isJsonPrimitive
public boolean isJsonPrimitive()
From source file:org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter.java
License:Open Source License
private boolean isValid(JsonElement jsonElement, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) { Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition); ToscaPropertyType toscaPropertyType = null; if ((toscaPropertyType = isDataTypeDerviedFromScalarType(dataTypeDefinition)) != null) { PropertyTypeValidator validator = toscaPropertyType.getValidator(); if (jsonElement == null || true == jsonElement.isJsonNull()) { boolean valid = validator.isValid(null, null, allDataTypes); if (false == valid) { log.trace("Failed in validation of property " + dataTypeDefinition.getName() + " from type " + dataTypeDefinition.getName()); return false; }//w w w.jav a2 s . c o m return true; } else { if (true == jsonElement.isJsonPrimitive()) { String value = null; if (jsonElement != null) { if (jsonElement.toString().isEmpty()) { value = ""; } else { value = jsonElement.toString(); } } boolean valid = validator.isValid(value, null, allDataTypes); if (false == valid) { log.trace("Failed in validation of property {} from type {}. Json primitive value is {}", dataTypeDefinition.getName(), dataTypeDefinition.getName(), value); return false; } return true; } else { // MAP, LIST, OTHER types cannot be applied data type // definition scalar type. We currently cannot derived from // map/list. (cannot add the entry schema to it) log.debug( "We cannot derive from list/map. Thus, the value cannot be not primitive since the data type {} is scalar one", dataTypeDefinition.getName()); return false; } } } else { if (jsonElement == null || jsonElement.isJsonNull()) { return true; } else { if (jsonElement.isJsonObject()) { JsonObject asJsonObject = jsonElement.getAsJsonObject(); Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet(); for (Entry<String, JsonElement> entry : entrySet) { String propName = entry.getKey(); JsonElement elementValue = entry.getValue(); PropertyDefinition propertyDefinition = allProperties.get(propName); if (propertyDefinition == null) { log.debug("The property {} was not found under data tpye {}", propName, dataTypeDefinition.getName()); return false; } String type = propertyDefinition.getType(); boolean isScalarType = ToscaPropertyType.isScalarType(type); if (true == isScalarType) { ToscaPropertyType propertyType = ToscaPropertyType.isValidType(type); if (propertyType == null) { log.debug("cannot find the {} under default tosca property types", type); return false; } PropertyTypeValidator validator = propertyType.getValidator(); String innerType = null; if (propertyType == ToscaPropertyType.LIST || propertyType == ToscaPropertyType.MAP) { if (propertyDefinition.getSchema() != null && propertyDefinition.getSchema().getProperty() != null) { innerType = propertyDefinition.getSchema().getProperty().getType(); if (innerType == null) { log.debug("Property type {} must have inner type in its decleration.", propertyType); return false; } } } String value = null; if (elementValue != null) { if (elementValue.isJsonPrimitive() && elementValue.getAsString().isEmpty()) { value = ""; } else { value = elementValue.toString(); } } boolean isValid = validator.isValid(value, innerType, allDataTypes); if (false == isValid) { log.debug("Failed to validate the value {} from type {}", value, propertyType); return false; } } else { DataTypeDefinition typeDefinition = allDataTypes.get(type); if (typeDefinition == null) { log.debug("The data type {} canot be found in the given data type list.", type); return false; } boolean isValid = isValid(elementValue, typeDefinition, allDataTypes); if (false == isValid) { log.debug("Failed in validation of value {} from type {}", (elementValue != null ? elementValue.toString() : null), typeDefinition.getName()); return false; } } } return true; } else { log.debug("The value {} of type {} should be json object", (jsonElement != null ? jsonElement.toString() : null), dataTypeDefinition.getName()); return false; } } } }
From source file:org.openecomp.sdc.be.tosca.PropertyConvertor.java
License:Open Source License
public Object convertToToscaObject(String propertyType, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { log.debug("try to convert propertyType {} , value {}, innerType {}", propertyType, value, innerType); if (value == null) { return value; }//from w ww . j a va 2 s . c om ToscaMapValueConverter mapConverterInst = ToscaMapValueConverter.getInstance(); ToscaValueConverter innerConverter = null; Boolean isScalar = true; ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); if (type == null) { log.debug("isn't prederfined type, get from all data types"); DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType); if (innerType == null) { innerType = propertyType; } if ((type = mapConverterInst.isScalarType(dataTypeDefinition)) != null) { log.debug("This is scalar type. get suitable converter for type {}", type); innerConverter = type.getValueConverter(); } else { isScalar = false; } } else { ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(type.getType()); if (typeIfScalar == null) { isScalar = false; } innerConverter = type.getValueConverter(); if (ToscaPropertyType.STRING.equals(type) && value.startsWith("/")) { return innerConverter.convertToToscaValue(value, innerType, dataTypes); } } JsonElement jsonElement = null; try { StringReader reader = new StringReader(value); JsonReader jsonReader = new JsonReader(reader); jsonReader.setLenient(true); jsonElement = jsonParser.parse(jsonReader); if (value.equals("")) { return value; } if (jsonElement.isJsonPrimitive() && isScalar) { log.debug("It's well defined type. convert it"); ToscaValueConverter converter = type.getValueConverter(); return converter.convertToToscaValue(value, innerType, dataTypes); } else { log.debug("It's data type or inputs in primitive type. convert as map"); Object convertedValue; if (innerConverter != null && (ToscaPropertyType.MAP.equals(type) || ToscaPropertyType.LIST.equals(type))) { convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes); } else { if (isScalar) { // complex json for scalar type convertedValue = mapConverterInst.handleComplexJsonValue(jsonElement); } else { if (innerConverter != null) { convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes); } else { convertedValue = mapConverterInst.convertDataTypeToToscaMap(innerType, dataTypes, innerConverter, isScalar, jsonElement); } } } return convertedValue; } } catch (JsonSyntaxException e) { log.debug("convertToToscaValue failed to parse json value :", e); return null; } }
From source file:org.openhab.binding.miele.handler.MieleBridgeHandler.java
License:Open Source License
protected JsonElement invokeRPC(String methodName, Object[] args) { int id = rand.nextInt(Integer.MAX_VALUE); JsonObject req = new JsonObject(); req.addProperty("jsonrpc", "2.0"); req.addProperty("id", id); req.addProperty("method", methodName); JsonElement result = null;/*www .j a v a 2 s .co m*/ JsonArray params = new JsonArray(); if (args != null) { for (Object o : args) { params.add(gson.toJsonTree(o)); } } req.add("params", params); String requestData = req.toString(); String responseData = null; try { responseData = post(url, headers, requestData); } catch (Exception e) { logger.error("An exception occurred while posting data : '{}'", e.getMessage()); } if (responseData != null) { logger.debug("The request '{}' yields '{}'", requestData, responseData); JsonParser parser = new JsonParser(); JsonObject resp = (JsonObject) parser.parse(new StringReader(responseData)); result = resp.get("result"); JsonElement error = resp.get("error"); if (error != null && !error.isJsonNull()) { if (error.isJsonPrimitive()) { logger.error("A remote exception occurred : '{}'", error.getAsString()); } else if (error.isJsonObject()) { JsonObject o = error.getAsJsonObject(); Integer code = (o.has("code") ? o.get("code").getAsInt() : null); String message = (o.has("message") ? o.get("message").getAsString() : null); String data = (o.has("data") ? (o.get("data") instanceof JsonObject ? o.get("data").toString() : o.get("data").getAsString()) : null); logger.error("A remote exception occurred : '{}':'{}':'{}'", new Object[] { code, message, data }); } else { logger.error("An unknown remote exception occurred : '{}'", error.toString()); } } } return result; }
From source file:org.openhab.binding.miele.internal.handler.MieleBridgeHandler.java
License:Open Source License
protected JsonElement invokeRPC(String methodName, Object[] args) { int id = rand.nextInt(Integer.MAX_VALUE); JsonObject req = new JsonObject(); req.addProperty("jsonrpc", "2.0"); req.addProperty("id", id); req.addProperty("method", methodName); JsonElement result = null;/* w w w.j av a2s . co m*/ JsonArray params = new JsonArray(); if (args != null) { for (Object o : args) { params.add(gson.toJsonTree(o)); } } req.add("params", params); String requestData = req.toString(); String responseData = null; try { responseData = post(url, headers, requestData); } catch (Exception e) { logger.debug("An exception occurred while posting data : '{}'", e.getMessage()); } if (responseData != null) { logger.debug("The request '{}' yields '{}'", requestData, responseData); JsonParser parser = new JsonParser(); JsonObject resp = (JsonObject) parser.parse(new StringReader(responseData)); result = resp.get("result"); JsonElement error = resp.get("error"); if (error != null && !error.isJsonNull()) { if (error.isJsonPrimitive()) { logger.debug("A remote exception occurred: '{}'", error.getAsString()); } else if (error.isJsonObject()) { JsonObject o = error.getAsJsonObject(); Integer code = (o.has("code") ? o.get("code").getAsInt() : null); String message = (o.has("message") ? o.get("message").getAsString() : null); String data = (o.has("data") ? (o.get("data") instanceof JsonObject ? o.get("data").toString() : o.get("data").getAsString()) : null); logger.debug("A remote exception occurred: '{}':'{}':'{}'", code, message, data); } else { logger.debug("An unknown remote exception occurred: '{}'", error.toString()); } } } return result; }
From source file:org.openo.commontosca.catalog.common.ToolUtil.java
License:Apache License
/** * @param value//from w ww .j ava 2 s . c om * @return */ public static String getAsString(JsonElement value) { if (value.isJsonPrimitive()) { return value.getAsString(); } return value.toString(); }
From source file:org.openqa.selenium.json.JsonToBeanConverter.java
License:Apache License
@SuppressWarnings("unchecked") private <T> T convert(Class<T> clazz, Object source, int depth) { if (source == null || source instanceof JsonNull) { return null; }// w w w . j av a2 s. c o m if (source instanceof JsonElement) { JsonElement json = (JsonElement) source; if (json.isJsonPrimitive()) { JsonPrimitive jp = json.getAsJsonPrimitive(); if (String.class.equals(clazz)) { return (T) jp.getAsString(); } if (jp.isNumber()) { if (Integer.class.isAssignableFrom(clazz) || int.class.equals(clazz)) { return (T) Integer.valueOf(jp.getAsNumber().intValue()); } else if (Long.class.isAssignableFrom(clazz) || long.class.equals(clazz)) { return (T) Long.valueOf(jp.getAsNumber().longValue()); } else if (Float.class.isAssignableFrom(clazz) || float.class.equals(clazz)) { return (T) Float.valueOf(jp.getAsNumber().floatValue()); } else if (Double.class.isAssignableFrom(clazz) || double.class.equals(clazz)) { return (T) Double.valueOf(jp.getAsNumber().doubleValue()); } else { return (T) convertJsonPrimitive(jp); } } } } if (isPrimitive(source.getClass())) { return (T) source; } if (isEnum(clazz, source)) { return (T) convertEnum(clazz, source); } if ("".equals(String.valueOf(source))) { return (T) source; } if (Command.class.equals(clazz)) { JsonObject json = new JsonParser().parse((String) source).getAsJsonObject(); SessionId sessionId = null; if (json.has("sessionId") && !json.get("sessionId").isJsonNull()) { sessionId = convert(SessionId.class, json.get("sessionId"), depth + 1); } String name = json.get("name").getAsString(); if (json.has("parameters")) { Map<String, ?> args = (Map<String, ?>) convert(HashMap.class, json.get("parameters"), depth + 1); return (T) new Command(sessionId, name, args); } return (T) new Command(sessionId, name); } if (Response.class.equals(clazz)) { Response response = new Response(); JsonObject json = source instanceof JsonObject ? (JsonObject) source : new JsonParser().parse((String) source).getAsJsonObject(); if (json.has("error") && !json.get("error").isJsonNull()) { String state = json.get("error").getAsString(); response.setState(state); response.setStatus(errorCodes.toStatus(state, Optional.empty())); response.setValue(convert(Object.class, json.get("message"))); } if (json.has("state") && !json.get("state").isJsonNull()) { String state = json.get("state").getAsString(); response.setState(state); response.setStatus(errorCodes.toStatus(state, Optional.empty())); } if (json.has("status") && !json.get("status").isJsonNull()) { JsonElement status = json.get("status"); if (status.getAsJsonPrimitive().isString()) { String state = status.getAsString(); response.setState(state); response.setStatus(errorCodes.toStatus(state, Optional.empty())); } else { int intStatus = status.getAsInt(); response.setState(errorCodes.toState(intStatus)); response.setStatus(intStatus); } } if (json.has("sessionId") && !json.get("sessionId").isJsonNull()) { response.setSessionId(json.get("sessionId").getAsString()); } if (json.has("value")) { response.setValue(convert(Object.class, json.get("value"))); } else { response.setValue(convert(Object.class, json)); } return (T) response; } if (SessionId.class.equals(clazz)) { // Stupid heuristic to tell if we are dealing with a selenium 2 or 3 session id. JsonElement json = source instanceof String ? new JsonParser().parse((String) source).getAsJsonObject() : (JsonElement) source; if (json.isJsonPrimitive()) { return (T) new SessionId(json.getAsString()); } return (T) new SessionId(json.getAsJsonObject().get("value").getAsString()); } if (Capabilities.class.isAssignableFrom(clazz)) { JsonObject json = source instanceof JsonElement ? ((JsonElement) source).getAsJsonObject() : new JsonParser().parse(source.toString()).getAsJsonObject(); Map<String, Object> map = convertMap(json.getAsJsonObject(), depth); return (T) new MutableCapabilities(map); } if (Date.class.equals(clazz)) { return (T) new Date(Long.valueOf(String.valueOf(source))); } if (source instanceof String && !((String) source).startsWith("{") && Object.class.equals(clazz)) { return (T) source; } Method fromJson = getMethod(clazz, "fromJson"); if (fromJson != null) { try { return (T) fromJson.invoke(null, source.toString()); } catch (ReflectiveOperationException e) { throw new WebDriverException(e); } } if (depth == 0) { if (source instanceof String) { source = new JsonParser().parse((String) source); } } if (source instanceof JsonElement) { JsonElement element = (JsonElement) source; if (element.isJsonNull()) { return null; } if (element.isJsonPrimitive()) { return (T) convertJsonPrimitive(element.getAsJsonPrimitive()); } if (element.isJsonArray()) { return (T) convertList(element.getAsJsonArray(), depth); } if (element.isJsonObject()) { if (Map.class.isAssignableFrom(clazz)) { return (T) convertMap(element.getAsJsonObject(), depth); } if (Object.class.equals(clazz)) { return (T) convertMap(element.getAsJsonObject(), depth); } return convertBean(clazz, element.getAsJsonObject(), depth); } } return (T) source; // Crap shoot here; probably a string. }
From source file:org.openqa.selenium.remote.JsonToBeanConverter.java
License:Apache License
@SuppressWarnings("unchecked") private <T> T convert(Class<T> clazz, Object source, int depth) { if (source == null || source instanceof JsonNull) { return null; }//from w ww .j a va 2s .c o m if (source instanceof JsonElement) { JsonElement json = (JsonElement) source; if (json.isJsonPrimitive()) { JsonPrimitive jp = json.getAsJsonPrimitive(); if (String.class.equals(clazz)) { return (T) jp.getAsString(); } if (jp.isNumber()) { if (Integer.class.isAssignableFrom(clazz) || int.class.equals(clazz)) { return (T) Integer.valueOf(jp.getAsNumber().intValue()); } else if (Long.class.isAssignableFrom(clazz) || long.class.equals(clazz)) { return (T) Long.valueOf(jp.getAsNumber().longValue()); } else if (Float.class.isAssignableFrom(clazz) || float.class.equals(clazz)) { return (T) Float.valueOf(jp.getAsNumber().floatValue()); } else if (Double.class.isAssignableFrom(clazz) || double.class.equals(clazz)) { return (T) Double.valueOf(jp.getAsNumber().doubleValue()); } else { return (T) convertJsonPrimitive(jp); } } } } if (isPrimitive(source.getClass())) { return (T) source; } if (isEnum(clazz, source)) { return (T) convertEnum(clazz, source); } if ("".equals(String.valueOf(source))) { return (T) source; } if (Command.class.equals(clazz)) { JsonObject json = new JsonParser().parse((String) source).getAsJsonObject(); SessionId sessionId = null; if (json.has("sessionId") && !json.get("sessionId").isJsonNull()) { sessionId = convert(SessionId.class, json.get("sessionId"), depth + 1); } String name = json.get("name").getAsString(); if (json.has("parameters")) { Map<String, ?> args = (Map<String, ?>) convert(HashMap.class, json.get("parameters"), depth + 1); return (T) new Command(sessionId, name, args); } return (T) new Command(sessionId, name); } if (Response.class.equals(clazz)) { Response response = new Response(); JsonObject json = source instanceof JsonObject ? (JsonObject) source : new JsonParser().parse((String) source).getAsJsonObject(); if (json.has("error") && !json.get("error").isJsonNull()) { String state = json.get("error").getAsString(); response.setState(state); response.setStatus(errorCodes.toStatus(state, Optional.empty())); response.setValue(convert(Object.class, json.get("message"))); } if (json.has("state") && !json.get("state").isJsonNull()) { String state = json.get("state").getAsString(); response.setState(state); response.setStatus(errorCodes.toStatus(state, Optional.empty())); } if (json.has("status") && !json.get("status").isJsonNull()) { JsonElement status = json.get("status"); if (status.getAsJsonPrimitive().isString()) { String state = status.getAsString(); response.setState(state); response.setStatus(errorCodes.toStatus(state, Optional.empty())); } else { int intStatus = status.getAsInt(); response.setState(errorCodes.toState(intStatus)); response.setStatus(intStatus); } } if (json.has("sessionId") && !json.get("sessionId").isJsonNull()) { response.setSessionId(json.get("sessionId").getAsString()); } if (json.has("value")) { response.setValue(convert(Object.class, json.get("value"))); } else { response.setValue(convert(Object.class, json)); } return (T) response; } if (SessionId.class.equals(clazz)) { // Stupid heuristic to tell if we are dealing with a selenium 2 or 3 session id. JsonElement json = source instanceof String ? new JsonParser().parse((String) source).getAsJsonObject() : (JsonElement) source; if (json.isJsonPrimitive()) { return (T) new SessionId(json.getAsString()); } return (T) new SessionId(json.getAsJsonObject().get("value").getAsString()); } if (Capabilities.class.isAssignableFrom(clazz)) { JsonObject json = source instanceof JsonElement ? ((JsonElement) source).getAsJsonObject() : new JsonParser().parse(source.toString()).getAsJsonObject(); Map<String, Object> map = convertMap(json.getAsJsonObject(), depth); return (T) new DesiredCapabilities(map); } if (Date.class.equals(clazz)) { return (T) new Date(Long.valueOf(String.valueOf(source))); } if (source instanceof String && !((String) source).startsWith("{") && Object.class.equals(clazz)) { return (T) source; } Method fromJson = getMethod(clazz, "fromJson"); if (fromJson != null) { try { return (T) fromJson.invoke(null, source.toString()); } catch (IllegalArgumentException e) { throw new WebDriverException(e); } catch (IllegalAccessException e) { throw new WebDriverException(e); } catch (InvocationTargetException e) { throw new WebDriverException(e); } } if (depth == 0) { if (source instanceof String) { source = new JsonParser().parse((String) source); } } if (source instanceof JsonElement) { JsonElement element = (JsonElement) source; if (element.isJsonNull()) { return null; } if (element.isJsonPrimitive()) { return (T) convertJsonPrimitive(element.getAsJsonPrimitive()); } if (element.isJsonArray()) { return (T) convertList(element.getAsJsonArray(), depth); } if (element.isJsonObject()) { if (Map.class.isAssignableFrom(clazz)) { return (T) convertMap(element.getAsJsonObject(), depth); } if (Object.class.equals(clazz)) { return (T) convertMap(element.getAsJsonObject(), depth); } return convertBean(clazz, element.getAsJsonObject(), depth); } } return (T) source; // Crap shoot here; probably a string. }
From source file:org.openscore.content.json.actions.GetValueFromObject.java
License:Open Source License
/** * This operation accepts an object in the JavaScript Object Notation format (JSON) and returns a value for the specified key. * * @param object The string representation of a JSON object. * Objects in JSON are a collection of name value pairs, separated by a colon and surrounded with curly brackets {}. * The name must be a string value, and the value can be a single string or any valid JSON object or array. * Examples: {"one":1, "two":2}, {"one":{"a":"a","B":"B"}, "two":"two", "three":[1,2,3.4]} * @param key The key in the object to get the value of. * Examples: city, location[0].city * @return a map containing the output of the operation. Keys present in the map are: * <p/>// ww w . ja v a 2 s . com * <br><br><b>returnResult</b> - This will contain the value for the specified key in the object. * <br><b>exception</b> - In case of success response, this result is empty. In case of failure response, * this result contains the java stack trace of the runtime exception. * <br><br><b>returnCode</b> - The returnCode of the operation: 0 for success, -1 for failure. */ @Action(name = "Get Value from Object", outputs = { @Output(Constants.OutputNames.RETURN_RESULT), @Output(Constants.OutputNames.RETURN_CODE), @Output(Constants.OutputNames.EXCEPTION) }, responses = { @Response(text = Constants.ResponseNames.SUCCESS, field = Constants.OutputNames.RETURN_CODE, value = Constants.ReturnCodes.RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED), @Response(text = Constants.ResponseNames.FAILURE, field = Constants.OutputNames.RETURN_CODE, value = Constants.ReturnCodes.RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true) }) public Map<String, String> execute(@Param(value = Constants.InputNames.OBJECT, required = true) String object, @Param(value = Constants.InputNames.KEY, required = true) String key) { Map<String, String> returnResult = new HashMap<>(); if (isBlank(object)) { return populateResult(returnResult, new Exception("Empty object provided!")); } if (key == null) { return populateResult(returnResult, new Exception("Null key provided!")); } JsonParser jsonParser = new JsonParser(); JsonElement jsonElement; JsonObject jsonRoot; try { jsonElement = jsonParser.parse(object); jsonRoot = jsonElement.getAsJsonObject(); } catch (Exception exception) { final String value = "Invalid object provided! " + exception.getMessage(); return populateResult(returnResult, value, exception); } int startIndex = 0; final JsonElement valueFromObject; try { valueFromObject = getObject(jsonRoot, key.split(ESCAPED_SLASH + "."), startIndex); } catch (Exception exception) { return populateResult(returnResult, exception); } if (valueFromObject.isJsonPrimitive()) { return populateResult(returnResult, valueFromObject.getAsString(), null); } else { return populateResult(returnResult, valueFromObject.toString(), null); } }
From source file:org.plos.crepo.model.metadata.RepoMetadata.java
License:Open Source License
@VisibleForTesting static Object convertJsonToImmutable(JsonElement element) { if (element.isJsonNull()) { return null; }/*from w w w.j av a2 s .com*/ if (element.isJsonPrimitive()) { JsonPrimitive primitive = element.getAsJsonPrimitive(); if (primitive.isString()) return primitive.getAsString(); if (primitive.isNumber()) return asNumber(primitive); if (primitive.isBoolean()) return primitive.getAsBoolean(); throw new RuntimeException("JsonPrimitive is not one of the expected primitive types"); } if (element.isJsonArray()) { JsonArray array = element.getAsJsonArray(); if (array.size() == 0) return Collections.emptyList(); List<Object> convertedList = new ArrayList<>(array.size()); for (JsonElement arrayElement : array) { Object convertedElement = convertJsonToImmutable(arrayElement); convertedList.add(convertedElement); } return Collections.unmodifiableList(convertedList); } if (element.isJsonObject()) { Set<Map.Entry<String, JsonElement>> entries = element.getAsJsonObject().entrySet(); if (entries.size() == 0) return Collections.emptyMap(); Map<String, Object> convertedMap = Maps.newHashMapWithExpectedSize(entries.size()); for (Map.Entry<String, JsonElement> entry : entries) { String key = Preconditions.checkNotNull(entry.getKey()); Object value = convertJsonToImmutable(entry.getValue()); convertedMap.put(key, value); } return Collections.unmodifiableMap(convertedMap); } throw new RuntimeException("JsonElement is not one of the expected subtypes"); }
From source file:org.ppojo.data.ArtifactSerializer.java
License:Apache License
private String readStringProperty(JsonElement json, String artifact_name, String propertyName, boolean isRequired, String defaultValue) { JsonElement typeElement = json.getAsJsonObject().get(propertyName); if (typeElement == null) if (isRequired) throw new RequiredPropertyMissing("Required property " + propertyName + " is missing in artifact " + artifact_name + " declaration in " + getDeserializeFilePath()); else/*from w ww . java 2 s .c o m*/ return defaultValue; if (!typeElement.isJsonPrimitive() || !typeElement.getAsJsonPrimitive().isString()) throw new JsonParseException("Invalid element type for property: " + propertyName + " in artifact " + artifact_name + ", expected String got " + JsonElementTypes.getType(typeElement) + ", in " + getDeserializeFilePath()); return typeElement.getAsString(); }