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

The following examples show how to use com.google.gson.JsonElement#getAsString() . 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 Project: supbot   File: Configuration.java    License: 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 2
Source Project: arcusplatform   File: MetricsServer.java    License: Apache License 2.0 6 votes vote down vote up
private void reportHistogram(JsonArray output, JsonObject metric, double ts, JsonObject tags) throws Exception {
   JsonElement jname = metric.get("name");
   if (jname == null || jname.isJsonNull()) {
      return;
   }
   tags = getAndMergeTags(metric, tags);

   String name = jname.getAsString();
   reportEntry(output, metric, ts, tags, name, "count");
   reportEntry(output, metric, ts, tags, name, "min");
   reportEntry(output, metric, ts, tags, name, "max");
   reportEntry(output, metric, ts, tags, name, "mean");
   reportEntry(output, metric, ts, tags, name, "stddev");
   reportEntry(output, metric, ts, tags, name, "p50");
   reportEntry(output, metric, ts, tags, name, "p75");
   reportEntry(output, metric, ts, tags, name, "p95");
   reportEntry(output, metric, ts, tags, name, "p98");
   reportEntry(output, metric, ts, tags, name, "p99");
   reportEntry(output, metric, ts, tags, name, "p999");
}
 
Example 3
Source Project: Insights   File: AgentDataSubscriber.java    License: Apache License 2.0 5 votes vote down vote up
private String buildPropertyConstraintQueryPart(JsonObject json, String memberName) {
	StringBuffer cypherQuery = new StringBuffer();
	if (json.has(memberName)) {
		JsonArray properties = json.getAsJsonArray(memberName);
		cypherQuery.append("{");
		for (JsonElement constraint : properties) {
			String fieldName = constraint.getAsString();
			cypherQuery.append(fieldName).append(" : properties.").append(fieldName).append(",");
			Neo4jFieldIndexRegistry.getInstance().syncFieldIndex(toolName, fieldName);
		}
		cypherQuery.delete(cypherQuery.length() - 1, cypherQuery.length());
		cypherQuery.append(" }");
	}
	return cypherQuery.toString();
}
 
Example 4
@Override
public Date deserialize(JsonElement element, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
    String date = element.getAsString();

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    formatter.setTimeZone(TimeZone.getTimeZone("UTC"));

    try {
        return formatter.parse(date);
    } catch (ParseException e) {
        return null;
    }
}
 
Example 5
Source Project: swagger-aem   File: JSON.java    License: Apache License 2.0 5 votes vote down vote up
private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) {
    JsonElement element = readElement.getAsJsonObject().get(discriminatorField);
    if(null == element) {
        throw new IllegalArgumentException("missing discriminator field: <" + discriminatorField + ">");
    }
    return element.getAsString();
}
 
Example 6
@Override public Message deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    if (mDebug) {
        Log.d("MessageDeserializer", "Got message: " + json.toString());
    }

    JsonObject jsonObject = json.getAsJsonObject();

    Class<? extends Message> klass;

    if (jsonObject.has("_reqid") && !jsonObject.get("_reqid").isJsonNull()) {
       klass = ResponseMessage.class;
    } else {
        JsonElement messageType = jsonObject.get("type");
        if (messageType != null) {
            String type = messageType.getAsString();
            klass = TYPES.get(type);
            if (klass == null) {
                klass = UnknownMessage.class;
            }
        } else {
            klass = UnknownMessage.class;
        }
    }

    return context.deserialize(json, klass);
}
 
Example 7
@Override
public VersionRange deserialize(JsonElement jsonElement, Type type,
    JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
  String versionRangeAsStr = jsonElement.getAsString();
  if (versionRangeAsStr != null) {
    return new VersionParser(emptyList()).parseRange(versionRangeAsStr);
  }
  return null;
}
 
Example 8
@Override
public BaseComponent deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    if (json.isJsonPrimitive()) {
        return new TextComponent(json.getAsString());
    }
    JsonObject object = json.getAsJsonObject();
    if (object.has("translate")) {
        return (BaseComponent)context.deserialize(json, TranslatableComponent.class);
    }
    return (BaseComponent)context.deserialize(json, TextComponent.class);
}
 
Example 9
Source Project: TabooLib   File: I18n20w14a.java    License: MIT License 5 votes vote down vote up
@Override
public String getName(Player player, Entity entity) {
    JsonObject locale = cache.get(player == null ? "zh_cn" : player.getLocale());
    if (locale == null) {
        locale = cache.get("en_gb");
    }
    if (locale == null) {
        return "[ERROR LOCALE]";
    }
    JsonElement element = locale.get(NMS.handle().getName(entity));
    return element == null ? entity.getName() : element.getAsString();
}
 
Example 10
private String loadJS(JsonElement e) {
  if (e == null)
    return null;
  if (!(e instanceof JsonPrimitive))
    return null;
  String s = e.getAsString();
  if ("".equals(s))
    return null;
  return s;
}
 
Example 11
Source Project: org.hl7.fhir.core   File: JsonParser.java    License: Apache License 2.0 5 votes vote down vote up
private void parseResource(String npath, JsonObject res, Element parent, Property elementProperty) throws FHIRException {
	JsonElement rt = res.get("resourceType");
	if (rt == null) {
		logError(line(res), col(res), npath, IssueType.INVALID, "Unable to find resourceType property", IssueSeverity.FATAL);
	} else {
		String name = rt.getAsString();
		StructureDefinition sd = context.fetchResource(StructureDefinition.class, ProfileUtilities.sdNs(name, context.getOverrideVersionNs()));
		if (sd == null)
			throw new FHIRFormatError("Contained resource does not appear to be a FHIR resource (unknown name '"+name+"')");
		parent.updateProperty(new Property(context, sd.getSnapshot().getElement().get(0), sd), SpecialElement.fromProperty(parent.getProperty()), elementProperty);
		parent.setType(name);
		parseChildren(npath, res, parent, true);
	}
}
 
Example 12
Source Project: pippo   File: GsonEngine.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public synchronized Date deserialize(JsonElement jsonElement, Type type,
                                     JsonDeserializationContext jsonDeserializationContext) {
    try {
        synchronized (dateTimeFormat) {
            Date date = dateTimeFormat.parse(jsonElement.getAsString());
            return new Date((date.getTime() / 1000) * 1000);
        }
    } catch (ParseException e) {
        throw new JsonSyntaxException(jsonElement.getAsString(), e);
    }
}
 
Example 13
Source Project: trex-stateless-gui   File: TrexEvent.java    License: Apache License 2.0 4 votes vote down vote up
public String getUser() {
    JsonElement who = data.get("who"); 
    return who != null ? who.getAsString() : null;
}
 
Example 14
/**
 * A utility method to handle null values and JsonNull values.
 */
String getAsString(String name) {
  final JsonElement element = json.get(name);
  return (element == null || element == JsonNull.INSTANCE) ? null : element.getAsString();
}
 
Example 15
public String getUserPostNo(JsonObject responseJson) {
    JsonElement id = responseJson.get(RESPONSE_NO); // \/test\/res\/1234.html#4321
    String userPostNo = id.getAsString();
    return userPostNo;
}
 
Example 16
/**
 * Reference the actual Dart DiagnosticsNode object this object is referencing.
 */
public InspectorInstanceRef getDartDiagnosticRef() {
  final JsonElement objectId = json.get("objectId");
  return new InspectorInstanceRef(objectId.isJsonNull() ? null : objectId.getAsString());
}
 
Example 17
@Override
public IChatBaseComponent deserialize(JsonElement element, Type type, JsonDeserializationContext ctx) throws JsonParseException {
    if (element.isJsonPrimitive()) {
        return new ChatComponentText(element.getAsString());
    } else if (!element.isJsonObject()) {
        if (element.isJsonArray()) {
            JsonArray jsonArray = element.getAsJsonArray();
            IChatBaseComponent chatcomp = null;
            for (JsonElement jsonElement : jsonArray) {
                IChatBaseComponent innerchatcomp = deserialize(jsonElement, jsonElement.getClass(), ctx);
                if (chatcomp == null) {
                    chatcomp = innerchatcomp;
                } else {
                    chatcomp.addSibling(innerchatcomp);
                }
            }
            return chatcomp;
        } else {
            throw new JsonParseException("Don\'t know how to turn " + element.toString() + " into a Component");
        }
    } else {
        JsonObject jsonobject = element.getAsJsonObject();
        IChatBaseComponent resultComp;
        if (jsonobject.has("text")) {
            resultComp = new ChatComponentText(jsonobject.get("text").getAsString());
        } else if (jsonobject.has("translate")) {
            String translate = jsonobject.get("translate").getAsString();
            if (jsonobject.has("with")) {
                JsonArray withJsonArray = jsonobject.getAsJsonArray("with");
                Object[] array = new Object[withJsonArray.size()];

                for (int i = 0; i < array.length; ++i) {
                    array[i] = deserialize(withJsonArray.get(i), type, ctx);
                    if (array[i] instanceof ChatComponentText) {
                        ChatComponentText compText = (ChatComponentText) array[i];
                        if (compText.getChatModifier().g() && compText.a().isEmpty()) {
                            array[i] = compText.g();
                        }
                    }
                }

                resultComp = new ChatMessage(translate, array);
            } else {
                resultComp = new ChatMessage(translate);
            }
        } else if (jsonobject.has("score")) {
            JsonObject scoreJsonObject = jsonobject.getAsJsonObject("score");
            if (!scoreJsonObject.has("name") || !scoreJsonObject.has("objective")) {
                throw new JsonParseException("A score component needs a least a name and an objective");
            }

            resultComp = new ChatComponentScore(JsonHelper.getString(scoreJsonObject, "name"), JsonHelper.getString(scoreJsonObject, "objective"));
            if (scoreJsonObject.has("value")) {
                ((ChatComponentScore) resultComp).b(JsonHelper.getString(scoreJsonObject, "value"));
            }
        } else {
            if (!jsonobject.has("selector")) {
                throw new JsonParseException("Don\'t know how to turn " + element.toString() + " into a Component");
            }

            resultComp = new ChatComponentSelector(JsonHelper.getString(jsonobject, "selector"));
        }

        if (jsonobject.has("extra")) {
            JsonArray entryJsonArray = jsonobject.getAsJsonArray("extra");
            if (entryJsonArray.size() <= 0) {
                throw new JsonParseException("Unexpected empty array of components");
            }
            for (int i = 0; i < entryJsonArray.size(); ++i) {
                resultComp.addSibling(deserialize(entryJsonArray.get(i), type, ctx));
            }
        }

        resultComp.setChatModifier((ChatModifier) ctx.deserialize(element, ChatModifier.class));
        return resultComp;
    }
}
 
Example 18
/**
 * Returns a reference to the value the DiagnosticsNode object is describing.
 */
public InspectorInstanceRef getValueRef() {
  final JsonElement valueId = json.get("valueId");
  return new InspectorInstanceRef(valueId.isJsonNull() ? null : valueId.getAsString());
}
 
Example 19
/**
 * Search a string inside a JSON string matching the input path expression
 *
 * @param jsonString
 *            an encoded JSON string
 * @param paths
 *            path fragments
 * @return the matching string or null in case of no match.
 * @throws JsonPathNotFoundException if json path is invalid
 * @throws IOException if the underlying input source has IO issues during parsing
 */
public static String getTextValue(String jsonString, String... paths) throws JsonPathNotFoundException, IOException {
    if (paths != null && paths.length > 0) {
        JsonElement jsonElement = getChildNode(jsonString, paths);
        if (jsonElement != null) {
            return jsonElement.getAsString();
        }
    }

    throw new JsonPathNotFoundException();
}
 
Example 20
/**
 * Gson invokes this call-back method during deserialization when it encounters a field of the
 * specified type. <p>
 *
 * In the implementation of this call-back method, you should consider invoking
 * {@link JsonDeserializationContext#deserialize(JsonElement, Type)} method to create objects
 * for any non-trivial field of the returned object. However, you should never invoke it on the
 * the same type passing {@code json} since that will cause an infinite loop (Gson will call your
 * call-back method again).
 * @param json The Json data being deserialized
 * @param typeOfT The type of the Object to deserialize to
 * @return a deserialized object of the specified type typeOfT which is a subclass of {@code T}
 * @throws JsonParseException if json is not in the expected format of {@code typeOfT}
 */
@Override
public Period deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
    throws JsonParseException
{
  // Do not try to deserialize null or empty values
  if (json.getAsString() == null || json.getAsString().isEmpty())
  {
    return null;
  }
  final PeriodFormatter fmt = ISOPeriodFormat.standard();
  return fmt.parsePeriod(json.getAsString());
}