List of usage examples for com.google.gson JsonPrimitive isString
public boolean isString()
From source file:org.terasology.rendering.nui.widgets.models.JsonTreeConverter.java
License:Apache License
/** * @param name The name to be given to this node (if null, is replaced by a default name). * @param json The {@link JsonElement} to be converted to a {@link JsonTree}. * @return A tree representation of the JSON hierarchy. */// w ww . j a va2 s.c o m private static JsonTree serialize(String name, JsonElement json) { if (json.isJsonPrimitive()) { JsonPrimitive primitive = json.getAsJsonPrimitive(); if (primitive.isBoolean()) { return new JsonTree(new JsonTreeNode(name, json.getAsBoolean(), name != null ? JsonTreeNode.ElementType.KEY_VALUE_PAIR : JsonTreeNode.ElementType.VALUE)); } else if (primitive.isNumber()) { return new JsonTree(new JsonTreeNode(name, json.getAsNumber(), name != null ? JsonTreeNode.ElementType.KEY_VALUE_PAIR : JsonTreeNode.ElementType.VALUE)); } else if (primitive.isString()) { return new JsonTree(new JsonTreeNode(name, json.getAsString(), name != null ? JsonTreeNode.ElementType.KEY_VALUE_PAIR : JsonTreeNode.ElementType.VALUE)); } else { return new JsonTree(new JsonTreeNode(name, null, name != null ? JsonTreeNode.ElementType.KEY_VALUE_PAIR : JsonTreeNode.ElementType.VALUE)); } } else if (json.isJsonArray()) { JsonTree tree = new JsonTree(new JsonTreeNode(name, null, JsonTreeNode.ElementType.ARRAY)); JsonArray array = json.getAsJsonArray(); for (int i = 0; i < array.size(); i++) { tree.addChild(serialize(array.get(i))); } return tree; } else if (json.isJsonObject()) { JsonTree tree = new JsonTree(new JsonTreeNode(name, null, JsonTreeNode.ElementType.OBJECT)); JsonObject object = json.getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : object.entrySet()) { tree.addChild(serialize(entry.getKey(), entry.getValue())); } return tree; } else { return new JsonTree(new JsonTreeNode(name, null, JsonTreeNode.ElementType.NULL)); } }
From source file:org.terasology.rendering.nui.widgets.treeView.JsonTreeConverter.java
License:Apache License
/** * @param name The name to be given to this node (if null, is replaced by a default name). * @param json The {@link JsonElement} to be converted to a {@link JsonTree}. * @return A tree representation of the JSON hierarchy. *///from ww w. j av a 2s . c o m private static JsonTree serialize(String name, JsonElement json) { if (json.isJsonPrimitive()) { JsonPrimitive primitive = json.getAsJsonPrimitive(); if (primitive.isBoolean()) { return new JsonTree(new JsonTreeValue(name, json.getAsBoolean(), name != null ? JsonTreeValue.Type.KEY_VALUE_PAIR : JsonTreeValue.Type.VALUE)); } else if (primitive.isNumber()) { return new JsonTree(new JsonTreeValue(name, json.getAsNumber(), name != null ? JsonTreeValue.Type.KEY_VALUE_PAIR : JsonTreeValue.Type.VALUE)); } else if (primitive.isString()) { return new JsonTree(new JsonTreeValue(name, json.getAsString(), name != null ? JsonTreeValue.Type.KEY_VALUE_PAIR : JsonTreeValue.Type.VALUE)); } else { return new JsonTree(new JsonTreeValue(name, null, name != null ? JsonTreeValue.Type.KEY_VALUE_PAIR : JsonTreeValue.Type.VALUE)); } } else if (json.isJsonArray()) { JsonTree tree = new JsonTree(new JsonTreeValue(name, null, JsonTreeValue.Type.ARRAY)); JsonArray array = json.getAsJsonArray(); for (int i = 0; i < array.size(); i++) { tree.addChild(serialize(array.get(i))); } return tree; } else if (json.isJsonObject()) { JsonTree tree = new JsonTree(new JsonTreeValue(name, null, JsonTreeValue.Type.OBJECT)); JsonObject object = json.getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : object.entrySet()) { tree.addChild(serialize(entry.getKey(), entry.getValue())); } return tree; } else { return new JsonTree(new JsonTreeValue(name, null, JsonTreeValue.Type.NULL)); } }
From source file:org.testeditor.fixture.web.json.BrowserSetupReader.java
License:Open Source License
private BrowserSetting createBrowserSettting(Entry<String, JsonElement> browserSettingEntry) { BrowserSetting browserSetting = null; String key = browserSettingEntry.getKey(); JsonElement value = browserSettingEntry.getValue(); JsonPrimitive browserSettingAsJsonPrimitive = value.getAsJsonPrimitive(); if (browserSettingAsJsonPrimitive.isString()) { browserSetting = new BrowserSetting(key, value.getAsString()); } else if (browserSettingAsJsonPrimitive.isBoolean()) { browserSetting = new BrowserSetting(key, value.getAsBoolean()); } else if (browserSettingAsJsonPrimitive.isNumber()) { browserSetting = new BrowserSetting(key, value.getAsInt()); }//from w w w . java2 s. c om return browserSetting; }
From source file:org.thingsboard.rule.engine.action.TbCopyAttributesToEntityViewNode.java
License:Apache License
@Override public void onMsg(TbContext ctx, TbMsg msg) { if (DataConstants.ATTRIBUTES_UPDATED.equals(msg.getType()) || DataConstants.ATTRIBUTES_DELETED.equals(msg.getType()) || SessionMsgType.POST_ATTRIBUTES_REQUEST.name().equals(msg.getType())) { if (!msg.getMetaData().getData().isEmpty()) { long now = System.currentTimeMillis(); String scope = msg.getType().equals(SessionMsgType.POST_ATTRIBUTES_REQUEST.name()) ? DataConstants.CLIENT_SCOPE : msg.getMetaData().getValue("scope"); ListenableFuture<List<EntityView>> entityViewsFuture = ctx.getEntityViewService() .findEntityViewsByTenantIdAndEntityIdAsync(ctx.getTenantId(), msg.getOriginator()); DonAsynchron.withCallback(entityViewsFuture, entityViews -> { for (EntityView entityView : entityViews) { long startTime = entityView.getStartTimeMs(); long endTime = entityView.getEndTimeMs(); if ((endTime != 0 && endTime > now && startTime < now) || (endTime == 0 && startTime < now)) { if (DataConstants.ATTRIBUTES_UPDATED.equals(msg.getType()) || SessionMsgType.POST_ATTRIBUTES_REQUEST.name().equals(msg.getType())) { Set<AttributeKvEntry> attributes = JsonConverter .convertToAttributes(new JsonParser().parse(msg.getData())); List<AttributeKvEntry> filteredAttributes = attributes.stream().filter( attr -> attributeContainsInEntityView(scope, attr.getKey(), entityView)) .collect(Collectors.toList()); ctx.getTelemetryService().saveAndNotify(ctx.getTenantId(), entityView.getId(), scope, filteredAttributes, new FutureCallback<Void>() { @Override public void onSuccess(@Nullable Void result) { transformAndTellNext(ctx, msg, entityView); } @Override public void onFailure(Throwable t) { ctx.tellFailure(msg, t); } });//from w ww .j ava2 s .c om } else if (DataConstants.ATTRIBUTES_DELETED.equals(msg.getType())) { List<String> attributes = new ArrayList<>(); for (JsonElement element : new JsonParser().parse(msg.getData()).getAsJsonObject() .get("attributes").getAsJsonArray()) { if (element.isJsonPrimitive()) { JsonPrimitive value = element.getAsJsonPrimitive(); if (value.isString()) { attributes.add(value.getAsString()); } } } List<String> filteredAttributes = attributes.stream() .filter(attr -> attributeContainsInEntityView(scope, attr, entityView)) .collect(Collectors.toList()); if (filteredAttributes != null && !filteredAttributes.isEmpty()) { ctx.getAttributesService().removeAll(ctx.getTenantId(), entityView.getId(), scope, filteredAttributes); transformAndTellNext(ctx, msg, entityView); } } } } }, t -> ctx.tellFailure(msg, t)); } else { ctx.tellFailure(msg, new IllegalArgumentException("Message metadata is empty")); } } else { ctx.tellFailure(msg, new IllegalArgumentException("Unsupported msg type [" + msg.getType() + "]")); } }
From source file:org.thingsboard.server.common.transport.adaptor.JsonConverter.java
License:Apache License
private static List<KeyValueProto> parseProtoValues(JsonObject valuesObject) { List<KeyValueProto> result = new ArrayList<>(); for (Entry<String, JsonElement> valueEntry : valuesObject.entrySet()) { JsonElement element = valueEntry.getValue(); if (element.isJsonPrimitive()) { JsonPrimitive value = element.getAsJsonPrimitive(); if (value.isString()) { if (maxStringValueLength > 0 && value.getAsString().length() > maxStringValueLength) { String message = String.format( "String value length [%d] for key [%s] is greater than maximum allowed [%d]", value.getAsString().length(), valueEntry.getKey(), maxStringValueLength); throw new JsonSyntaxException(message); }/*from www.j av a 2s . com*/ if (isTypeCastEnabled && NumberUtils.isParsable(value.getAsString())) { try { result.add(buildNumericKeyValueProto(value, valueEntry.getKey())); } catch (RuntimeException th) { result.add(KeyValueProto.newBuilder().setKey(valueEntry.getKey()) .setType(KeyValueType.STRING_V).setStringV(value.getAsString()).build()); } } else { result.add(KeyValueProto.newBuilder().setKey(valueEntry.getKey()) .setType(KeyValueType.STRING_V).setStringV(value.getAsString()).build()); } } else if (value.isBoolean()) { result.add(KeyValueProto.newBuilder().setKey(valueEntry.getKey()) .setType(KeyValueType.BOOLEAN_V).setBoolV(value.getAsBoolean()).build()); } else if (value.isNumber()) { result.add(buildNumericKeyValueProto(value, valueEntry.getKey())); } else { throw new JsonSyntaxException(CAN_T_PARSE_VALUE + value); } } else { throw new JsonSyntaxException(CAN_T_PARSE_VALUE + element); } } return result; }
From source file:org.thingsboard.server.common.transport.adaptor.JsonConverter.java
License:Apache License
private static List<KvEntry> parseValues(JsonObject valuesObject) { List<KvEntry> result = new ArrayList<>(); for (Entry<String, JsonElement> valueEntry : valuesObject.entrySet()) { JsonElement element = valueEntry.getValue(); if (element.isJsonPrimitive()) { JsonPrimitive value = element.getAsJsonPrimitive(); if (value.isString()) { if (maxStringValueLength > 0 && value.getAsString().length() > maxStringValueLength) { String message = String.format( "String value length [%d] for key [%s] is greater than maximum allowed [%d]", value.getAsString().length(), valueEntry.getKey(), maxStringValueLength); throw new JsonSyntaxException(message); }//from w ww. ja v a2 s. co m if (isTypeCastEnabled && NumberUtils.isParsable(value.getAsString())) { try { parseNumericValue(result, valueEntry, value); } catch (RuntimeException th) { result.add(new StringDataEntry(valueEntry.getKey(), value.getAsString())); } } else { result.add(new StringDataEntry(valueEntry.getKey(), value.getAsString())); } } else if (value.isBoolean()) { result.add(new BooleanDataEntry(valueEntry.getKey(), value.getAsBoolean())); } else if (value.isNumber()) { parseNumericValue(result, valueEntry, value); } else { throw new JsonSyntaxException(CAN_T_PARSE_VALUE + value); } } else { throw new JsonSyntaxException(CAN_T_PARSE_VALUE + element); } } return result; }
From source file:org.trimou.gson.resolver.JsonElementResolver.java
License:Apache License
private Object unwrapJsonPrimitive(JsonPrimitive jsonPrimitive) { if (jsonPrimitive.isBoolean()) { return jsonPrimitive.getAsBoolean(); } else if (jsonPrimitive.isString()) { return jsonPrimitive.getAsString(); } else if (jsonPrimitive.isNumber()) { return jsonPrimitive.getAsNumber(); }//from w w w .j av a2 s . c o m return jsonPrimitive; }
From source file:org.tuleap.mylyn.task.core.internal.parser.AbstractTuleapDeserializer.java
License:Open Source License
/** * {@inheritDoc}//w ww. ja v a2s .com * * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, java.lang.reflect.Type, * com.google.gson.JsonDeserializationContext) */ @Override public T deserialize(JsonElement rootJsonElement, Type type, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = rootJsonElement.getAsJsonObject(); T pojo = super.deserialize(rootJsonElement, type, context); JsonElement jsonTrackerRef = jsonObject.get(ITuleapConstants.JSON_TRACKER); TuleapReference trackerRef = context.deserialize(jsonTrackerRef, TuleapReference.class); pojo.setTracker(trackerRef); JsonArray fields = jsonObject.get(ITuleapConstants.VALUES).getAsJsonArray(); for (JsonElement field : fields) { JsonObject jsonField = field.getAsJsonObject(); int fieldId = jsonField.get(ITuleapConstants.FIELD_ID).getAsInt(); if (jsonField.has(ITuleapConstants.FIELD_VALUE)) { JsonElement jsonValue = jsonField.get(ITuleapConstants.FIELD_VALUE); if (jsonValue.isJsonPrimitive()) { JsonPrimitive primitive = jsonValue.getAsJsonPrimitive(); if (primitive.isString()) { pojo.addFieldValue(new LiteralFieldValue(fieldId, primitive.getAsString())); } else if (primitive.isNumber()) { pojo.addFieldValue(new LiteralFieldValue(fieldId, String.valueOf(primitive.getAsNumber()))); } else if (primitive.isBoolean()) { pojo.addFieldValue( new LiteralFieldValue(fieldId, String.valueOf(primitive.getAsBoolean()))); } } } else if (jsonField.has(ITuleapConstants.FIELD_BIND_VALUE_ID) && !jsonField.get(ITuleapConstants.FIELD_BIND_VALUE_ID).isJsonNull()) { // sb? JsonElement jsonBindValueId = jsonField.get(ITuleapConstants.FIELD_BIND_VALUE_ID); int bindValueId = jsonBindValueId.getAsInt(); pojo.addFieldValue(new BoundFieldValue(fieldId, Lists.newArrayList(Integer.valueOf(bindValueId)))); } else if (jsonField.has(ITuleapConstants.FIELD_BIND_VALUE_IDS) && !jsonField.get(ITuleapConstants.FIELD_BIND_VALUE_IDS).isJsonNull()) { // sb?, msb, cb, or tbl (open list) JsonElement jsonBindValueIds = jsonField.get(ITuleapConstants.FIELD_BIND_VALUE_IDS); JsonArray jsonIds = jsonBindValueIds.getAsJsonArray(); if (jsonIds.size() > 0) { JsonPrimitive firstElement = jsonIds.get(0).getAsJsonPrimitive(); if (firstElement.isString()) { // Open list (tbl) List<String> bindValueIds = new ArrayList<String>(); for (JsonElement idElement : jsonIds) { bindValueIds.add(idElement.getAsString()); } pojo.addFieldValue(new OpenListFieldValue(fieldId, bindValueIds)); } else { List<Integer> bindValueIds = new ArrayList<Integer>(); for (JsonElement idElement : jsonIds) { bindValueIds.add(Integer.valueOf(idElement.getAsInt())); } pojo.addFieldValue(new BoundFieldValue(fieldId, bindValueIds)); } } else { pojo.addFieldValue(new BoundFieldValue(fieldId, Collections.<Integer>emptyList())); } } else if (jsonField.has(ITuleapConstants.FIELD_LINKS) && !jsonField.get(ITuleapConstants.FIELD_LINKS).isJsonNull()) { // Artifact links pojo.addFieldValue( context.<ArtifactLinkFieldValue>deserialize(jsonField, ArtifactLinkFieldValue.class)); } else if (jsonField.has(ITuleapConstants.FILE_DESCRIPTIONS) && jsonField.get(ITuleapConstants.FILE_DESCRIPTIONS).isJsonArray()) { AttachmentFieldValue value = context.deserialize(jsonField, AttachmentFieldValue.class); pojo.addFieldValue(value); } } return pojo; }
From source file:org.waveprotocol.wave.communication.gson.GsonUtil.java
License:Apache License
/** * Unpack a JsonElement into the object type * * @param <T> The type to deserialize * @param object The object used to accept the pare result * @param valueObj The root of a tree of JsonElements or an indirection index * @param gson A Gson context//from w ww . jav a 2 s . c o m * @param raw * @throws GsonException */ public static <T extends GsonSerializable> void extractJsonObject(T object, JsonElement valueObj, Gson gson, RawStringData raw) throws GsonException { if (valueObj.isJsonObject()) { object.fromGson(valueObj.getAsJsonObject(), gson, raw); } else if (valueObj.isJsonPrimitive()) { JsonPrimitive primitive = valueObj.getAsJsonPrimitive(); String s = null; if (raw == null || !primitive.isString()) { throw new GsonException("Decoding " + valueObj + " as object " + object.getClass() + " with no RawStringData given"); } s = raw.getString(valueObj.getAsString()); GsonUtil.parseJson(object, gson, s, raw); } else { throw new GsonException( "Cannot decode valueObject " + valueObj.getClass() + " as object " + object.getClass()); } }
From source file:org.wso2.ballerina.nativeimpl.lang.json.GetString.java
License:Open Source License
@Override public BValue[] execute(Context ctx) { String jsonPath = null;//from w w w . j a v a 2 s. co m BValue result = null; try { // Accessing Parameters. BJSON json = (BJSON) getArgument(ctx, 0); jsonPath = getArgument(ctx, 1).stringValue(); // Getting the value from JSON ReadContext jsonCtx = JsonPath.parse(json.value()); JsonElement element = jsonCtx.read(jsonPath); if (element == null) { throw new BallerinaException("No matching element found for jsonpath: " + jsonPath); } else if (element.isJsonPrimitive()) { // if the resulting value is a primitive, return the respective primitive value object JsonPrimitive value = element.getAsJsonPrimitive(); if (value.isString()) { result = new BString(value.getAsString()); } else { throw new BallerinaException("The element matching path: " + jsonPath + " is not a String."); } } else { throw new BallerinaException("The element matching path: " + jsonPath + " is not a String."); } } catch (PathNotFoundException e) { ErrorHandler.handleNonExistingJsonpPath(OPERATION, jsonPath, e); } catch (InvalidPathException e) { ErrorHandler.handleInvalidJsonPath(OPERATION, e); } catch (JsonPathException e) { ErrorHandler.handleJsonPathException(OPERATION, e); } catch (Throwable e) { ErrorHandler.handleJsonPathException(OPERATION, e); } // Setting output value. return getBValues(result); }