List of usage examples for com.google.gson JsonPrimitive isString
public boolean isString()
From source file:hdm.stuttgart.esell.router.GeneralObjectDeserializer.java
License:Apache License
public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (json.isJsonNull()) { return null; } else if (json.isJsonPrimitive()) { JsonPrimitive primitive = json.getAsJsonPrimitive(); if (primitive.isString()) { return primitive.getAsString(); } else if (primitive.isNumber()) { return primitive.getAsNumber(); } else if (primitive.isBoolean()) { return primitive.getAsBoolean(); }// w w w. ja va 2s. c om } else if (json.isJsonArray()) { JsonArray array = json.getAsJsonArray(); Object[] result = new Object[array.size()]; int i = 0; for (JsonElement element : array) { result[i] = deserialize(element, null, context); ++i; } return result; } else if (json.isJsonObject()) { JsonObject object = json.getAsJsonObject(); Map<String, Object> result = new HashMap<String, Object>(); for (Map.Entry<String, JsonElement> entry : object.entrySet()) { Object value = deserialize(entry.getValue(), null, context); result.put(entry.getKey(), value); } return result; } else { throw new JsonParseException("Unknown JSON type for JsonElement " + json.toString()); } return null; }
From source file:io.soliton.protobuf.json.JsonRpcRequest.java
License:Apache License
public static JsonRpcRequest fromJson(JsonElement root) throws JsonRpcError { if (!root.isJsonObject()) { throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Received payload is not a JSON Object"); }/*from ww w . j ava 2 s . c o m*/ JsonObject request = root.getAsJsonObject(); JsonElement id = request.get(JsonRpcProtocol.ID); JsonElement methodNameElement = request.get(JsonRpcProtocol.METHOD); JsonElement paramsElement = request.get(JsonRpcProtocol.PARAMETERS); if (id == null) { throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Malformed request, missing 'id' property"); } if (methodNameElement == null) { throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Malformed request, missing 'method' property"); } if (paramsElement == null) { throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Malformed request, missing 'params' property"); } if (!methodNameElement.isJsonPrimitive()) { throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Method name is not a JSON primitive"); } JsonPrimitive methodName = methodNameElement.getAsJsonPrimitive(); if (!methodName.isString()) { throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Method name is not a string"); } if (!paramsElement.isJsonArray()) { throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'params' property is not an array"); } JsonArray params = paramsElement.getAsJsonArray(); if (params.size() != 1) { throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'params' property is not an array"); } JsonElement paramElement = params.get(0); if (!paramElement.isJsonObject()) { throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Parameter is not an object"); } JsonObject parameter = paramElement.getAsJsonObject(); List<String> serviceAndMethod = Lists.newArrayList(DOT_SPLITTER.split(methodName.getAsString())); String methodNameString = methodName.getAsString(); int dotIndex = methodNameString.lastIndexOf('.'); if (dotIndex < 0) { throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'method' property is not properly formatted"); } if (dotIndex == methodNameString.length() - 1) { throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'method' property is not properly formatted"); } String service = methodNameString.substring(0, dotIndex); String method = methodNameString.substring(dotIndex + 1); if (service.isEmpty() || method.isEmpty()) { throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'method' property is not properly formatted"); } if (serviceAndMethod.size() < 2) { throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'method' property is not properly formatted"); } return new JsonRpcRequest(service, method, id, parameter); }
From source file:io.thinger.thinger.views.Element.java
License:Open Source License
public static Element createPrimitiveElement(String name, JsonPrimitive primitive, LinearLayout layout, boolean output) { if (primitive.isBoolean()) { return new BoolValue(layout, name, primitive.getAsBoolean(), output); } else if (primitive.isNumber()) { return new NumberValue(layout, name, primitive.getAsNumber(), output); } else if (primitive.isString()) { return new StringValue(layout, name, primitive.getAsString(), output); }/*from w w w .ja va2 s. c om*/ return null; }
From source file:it.polimi.tower4clouds.data_analyzer.DAInputDataUnmarshaller.java
License:Apache License
@Override public Model unmarshal(String inputData) throws Exception { // logger.debug("Unmarshalling data"); // long startTime = System.currentTimeMillis(); Model model = ModelFactory.createDefaultModel(); JsonArray jsonData = jsonParser.parse(inputData).getAsJsonArray(); // logger.debug("{} monitoring datum json object(s) received", // jsonData.size()); for (JsonElement jsonElement : jsonData) { JsonObject jsonDatum = jsonElement.getAsJsonObject(); Resource resourceDatum = model.createResource(UUID.randomUUID().toString()).addProperty(RDF.type, MO.MonitoringDatum);/*from ww w. j a va 2 s. c o m*/ for (Entry<String, JsonElement> pair : jsonDatum.entrySet()) { String property = pair.getKey(); JsonPrimitive value = pair.getValue().getAsJsonPrimitive(); if (value.isBoolean()) { resourceDatum.addProperty(MO.makeProperty(property), model.createTypedLiteral(value.getAsBoolean(), XSDDatatype.XSDboolean)); } else if (value.isString()) { resourceDatum.addProperty(MO.makeProperty(property), model.createTypedLiteral(value.getAsString(), XSDDatatype.XSDstring)); } else if (value.isNumber()) { resourceDatum.addProperty(MO.makeProperty(property), model.createTypedLiteral(value.getAsNumber().doubleValue(), XSDDatatype.XSDdouble)); } else { logger.error("Unknown datum property: {}", value); } } } // logger.debug("Unmarshalling completed in {} seconds", // ((double) (System.currentTimeMillis() - startTime)) / 1000); return model; }
From source file:jp.yokomark.utils.gson.utils.JsonElementUtils.java
License:Open Source License
public static String getAsStringOrThrow(JsonPrimitive primitive) throws JsonParseException { if (!primitive.isString()) { throw new JsonParseException("this primitive is not a json string: " + primitive); }/*from w w w.j a v a 2 s. c o m*/ return primitive.getAsString(); }
From source file:JsonParser.ParseJson.java
public static void dumpJSONElement(JsonElement element, String type) { if (element.isJsonObject()) { //System.out.println("Is an object"); JsonObject obj = element.getAsJsonObject(); java.util.Set<java.util.Map.Entry<String, JsonElement>> entries = obj.entrySet(); java.util.Iterator<java.util.Map.Entry<String, JsonElement>> iter = entries.iterator(); while (iter.hasNext()) { java.util.Map.Entry<String, JsonElement> entry = iter.next(); // System.out.println("Key: " + entry.getKey()); if (entry.getKey().toString().equals("instances")) { System.out.println("............Topic: "); dumpJSONElement(entry.getValue(), "topic"); }// www. ja va 2 s. c o m if (entry.getKey().toString().equals("aspects")) { System.out.println("............aspects: "); dumpJSONElement(entry.getValue(), "aspect"); } else if (entry.getKey().toString().equals("positives")) { System.out.println(".............Positive Words "); dumpJSONElement(entry.getValue(), "positive"); } else if (entry.getKey().toString().equals("negatives")) { System.out.println(".............negatives Words "); dumpJSONElement(entry.getValue(), "negative"); } else { dumpJSONElement(entry.getValue(), ""); } } } else if (element.isJsonArray()) { JsonArray array = element.getAsJsonArray(); //System.out.println("Is an array. Number of values: " + array.size()); java.util.Iterator<JsonElement> iter = array.iterator(); while (iter.hasNext()) { JsonElement entry = iter.next(); dumpJSONElement(entry, ""); } } else if (element.isJsonPrimitive()) { //System.out.println("Is a primitive"); JsonPrimitive value = element.getAsJsonPrimitive(); if (value.isBoolean()) { //System.out.println("Is boolean: " + value.getAsBoolean()); } else if (value.isNumber()) { // System.out.println("Is number: " + value.getAsNumber()); } else if (value.isString()) { //if(!value.getAsString().equals("empty")) //{ //if(type.equals("topic")) //{ System.out.println(type + " :" + value.getAsString()); //} } } else if (element.isJsonNull()) { System.out.println("Is NULL"); } else { System.out.println("Error. Unknown type of element"); } }
From source file:leola.web.WebLeolaLibrary.java
License:Open Source License
/** * Converts the {@link JsonElement} into the equivalent {@link LeoObject} * // w w w . j av a2s . c om * @param element * @return the {@link LeoObject} */ private static LeoObject toLeoObject(JsonElement element) { if (element == null || element.isJsonNull()) { return LeoObject.NULL; } if (element.isJsonArray()) { JsonArray array = element.getAsJsonArray(); LeoArray leoArray = new LeoArray(array.size()); array.forEach(e -> leoArray.add(toLeoObject(e))); return leoArray; } if (element.isJsonObject()) { JsonObject object = element.getAsJsonObject(); LeoMap leoMap = new LeoMap(); object.entrySet().forEach(entry -> { leoMap.putByString(entry.getKey(), toLeoObject(entry.getValue())); }); return leoMap; } if (element.isJsonPrimitive()) { JsonPrimitive primitive = element.getAsJsonPrimitive(); if (primitive.isBoolean()) { return LeoObject.valueOf(primitive.getAsBoolean()); } if (primitive.isNumber()) { return LeoObject.valueOf(primitive.getAsDouble()); } if (primitive.isString()) { return LeoString.valueOf(primitive.getAsString()); } } return LeoObject.NULL; }
From source file:me.boomboompower.togglechat.utils.BetterJsonObject.java
License:Open Source License
/** * The optional string 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 string/*from w w w . ja v a2 s. c om*/ * * @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 String optString(String key, String value) { if (key == null || key.isEmpty() || !has(key)) { return value; } JsonPrimitive primitive = asPrimitive(get(key)); if (primitive != null && primitive.isString()) { return primitive.getAsString(); } return value; }
From source file:net.doubledoordev.backend.util.JsonNBTHelper.java
License:Open Source License
/** * There is no way to detect number types and NBT is picky about this. Lets hope the original type id is there, otherwise we are royally screwed. *//*from w ww. j a v a 2 s. c o m*/ public static Tag parseJSON(JsonPrimitive element) { String string = element.getAsString(); if (string.contains(":")) { String[] split = string.split(":", 2); switch (TagType.getByTypeName(split[0])) { case TAG_END: return new EndTag(); case TAG_BYTE: return new ByteTag("", Byte.parseByte(split[1])); case TAG_SHORT: return new ShortTag("", Short.parseShort(split[1])); case TAG_INT: return new IntTag("", Integer.parseInt(split[1])); case TAG_LONG: return new LongTag("", Long.parseLong(split[1])); case TAG_FLOAT: return new FloatTag("", Float.parseFloat(split[1])); case TAG_DOUBLE: return new DoubleTag("", Double.parseDouble(split[1])); case TAG_BYTE_ARRAY: return parseJSONByteArray(split[1]); case TAG_STRING: return new StringTag("", split[1]); // TAG_LIST != JsonPrimitive // TAG_COMPOUND != JsonPrimitive case TAG_INT_ARRAY: return parseJSONIntArray(split[1]); case TAG_SHORT_ARRAY: return parseJSONShortArray(split[1]); } } // Now it becomes guesswork. if (element.isString()) return new StringTag("", string); if (element.isBoolean()) return new ByteTag("", element.getAsBoolean()); Number n = element.getAsNumber(); if (n instanceof Byte) return new ByteTag("", n.byteValue()); if (n instanceof Short) return new ShortTag("", n.shortValue()); if (n instanceof Integer) return new IntTag("", n.intValue()); if (n instanceof Long) return new LongTag("", n.longValue()); if (n instanceof Float) return new FloatTag("", n.floatValue()); if (n instanceof Double) return new DoubleTag("", n.doubleValue()); try { return new IntTag("", Integer.parseInt(element.toString())); } catch (NumberFormatException ignored) { } throw new NumberFormatException(element.getAsNumber() + " is was not able to be parsed."); }
From source file:net.doubledoordev.backend.util.JsonNBTHelper.java
License:Open Source License
public static JsonPrimitive fixNulls(JsonPrimitive primitive) { if (primitive.isBoolean()) return new JsonPrimitive(primitive.getAsBoolean()); if (primitive.isNumber()) return new JsonPrimitive(primitive.getAsNumber()); if (primitive.isString()) return new JsonPrimitive(primitive.getAsString()); return JSONPARSER.parse(primitive.toString()).getAsJsonPrimitive(); }