Java Code Examples for com.google.gson.JsonObject#get()

The following examples show how to use com.google.gson.JsonObject#get() . 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: JsonFunctions.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */
@SuppressWarnings("unused") @Deprecated 
private static Function<JsonElement, JsonElement> walkNOld(final Iterable<String> elements) {
    // TODO PERSISTENCE WORKAROUND
    return new Function<JsonElement, JsonElement>() {
        @Override public JsonElement apply(JsonElement input) {
            JsonElement curr = input;
            for (String element : elements) {
                if (curr==null) return null;
                JsonObject jo = curr.getAsJsonObject();
                curr = jo.get(element);
            }
            return curr;
        }
    };
}
 
Example 2
Source File: DeployGroupTypeAdapter.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
private List<DeployKey> makeKeys ( final DeployGroup group, final JsonObject obj, final JsonDeserializationContext ctx )
{
    final JsonElement keysEle = obj.get ( "keys" );
    if ( keysEle == null )
    {
        return Collections.emptyList ();
    }

    final JsonObject keys = keysEle.getAsJsonObject ();

    final List<DeployKey> result = new LinkedList<> ();

    for ( final Entry<String, JsonElement> entry : keys.entrySet () )
    {
        final JsonObject o2 = entry.getValue ().getAsJsonObject ();
        result.add ( new DeployKey ( group, entry.getKey (), o2.get ( "name" ).getAsString (), o2.get ( "key" ).getAsString (), getAsTimestamp ( ctx, o2 ) ) );
    }

    return result;
}
 
Example 3
Source File: JsonParser.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
public Element parse(JsonObject object) throws FHIRException {
	JsonElement rt = object.get("resourceType");
	if (rt == null) {
		logError(line(object), col(object), "$", IssueType.INVALID, "Unable to find resourceType property", IssueSeverity.FATAL);
		return null;
	} else {
		String name = rt.getAsString();
		String path = "/"+name;

		StructureDefinition sd = getDefinition(line(object), col(object), name);
		if (sd == null)
			return null;

		Element result = new Element(name, new Property(context, sd.getSnapshot().getElement().get(0), sd));
		checkObject(object, path);
		result.markLocation(line(object), col(object));
		result.setType(name);
		parseChildren(path, object, result, true);
		result.numberChildren();
		return result;
	}
}
 
Example 4
Source File: UriTaskProviderModelParser.java    From workspacemechanic with Eclipse Public License 1.0 5 votes vote down vote up
private String deserialize(JsonObject jo, String field) {
  JsonElement val = jo.get(field);
  if (val == null) {
    return null;
  }
  return val.getAsString();
}
 
Example 5
Source File: BooleanValue.java    From ClientBase with MIT License 5 votes vote down vote up
@Override
public void fromJsonObject(@NotNull JsonObject obj) {
    if (obj.has(getName())) {
        JsonElement element = obj.get(getName());

        if (element instanceof JsonPrimitive && ((JsonPrimitive) element).isBoolean()) {
            setObject(element.getAsBoolean());
        } else {
            throw new IllegalArgumentException("Entry '" + getName() + "' is not valid");
        }
    } else {
        throw new IllegalArgumentException("Object does not have '" + getName() + "'");
    }
}
 
Example 6
Source File: FeatureFactorySerializer.java    From quaerite with Apache License 2.0 5 votes vote down vote up
private FeatureFactory buildWeightableFeatureFactory(String paramName, JsonObject obj) {
    List<String> fields = toStringList(obj.get(FIELDS_KEY).getAsJsonArray());

    List<Float> defaultWeights = toFloatList(obj.get(DEFAULT_WEIGHT_KEY));
    int maxSetSizeInt = -1;
    if (obj.has(MAX_SET_SIZE_KEY)) {
        JsonElement maxSetSize = obj.get(MAX_SET_SIZE_KEY);
        if (!maxSetSize.isJsonNull() && maxSetSize.isJsonPrimitive()) {
            maxSetSizeInt = maxSetSize.getAsInt();
        }
    }
    int minSetSizeInt = -1;
    if (obj.has(MIN_SET_SIZE_KEY)) {
        JsonElement minSetSize = obj.get(MIN_SET_SIZE_KEY);
        if (!minSetSize.isJsonNull() && minSetSize.isJsonPrimitive()) {
            minSetSizeInt = minSetSize.getAsInt();
        }
    }
    Class clazz = null;
    try {
        clazz = Class.forName(getClassName(paramName));
    } catch (ClassNotFoundException e) {
        throw new RuntimeException();
    }
    return new WeightableListFeatureFactory(paramName, clazz, fields,
            defaultWeights, minSetSizeInt, maxSetSizeInt);
}
 
Example 7
Source File: ReflexJson.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private static ReflexActionSendPlatform convertPl(JsonObject pl, JsonDeserializationContext context) {
   String evt = pl.get("m").getAsString();
   Map<String,Object> args = context.deserialize(pl.get("a"), SEND_PLATFORM_ARGS);

   JsonElement rsp = pl.get("r");
   return new ReflexActionSendPlatform(evt, args, rsp != null && rsp.getAsBoolean());
}
 
Example 8
Source File: TmfIntervalDeserializer.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public ITmfStateInterval deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
    JsonObject object = json.getAsJsonObject();
    long start = object.get(TmfIntervalStrings.START).getAsLong();
    long end = object.get(TmfIntervalStrings.END).getAsLong();
    int quark = object.get(TmfIntervalStrings.QUARK).getAsInt();
    String type = object.get(TmfIntervalStrings.TYPE).getAsString();
    if (type.equals(TmfIntervalStrings.NULL)) {
        return new TmfStateInterval(start, end, quark, (Object) null);
    }
    JsonElement value = object.get(TmfIntervalStrings.VALUE);
    try {
        Class<?> typeClass = Class.forName(type);

        if (typeClass.isAssignableFrom(CustomStateValue.class)) {
            String encoded = value.getAsString();
            byte[] serialized = Base64.getDecoder().decode(encoded);
            ByteBuffer buffer = ByteBuffer.wrap(serialized);
            ISafeByteBufferReader sbbr = SafeByteBufferFactory.wrapReader(buffer, serialized.length);
            TmfStateValue sv = CustomStateValue.readSerializedValue(sbbr);
            return new TmfStateInterval(start, end, quark, sv.unboxValue());
        }
        if (typeClass.isAssignableFrom(Integer.class)) {
            return new TmfStateInterval(start, end, quark, value.getAsInt());
        } else if (typeClass.isAssignableFrom(Long.class)) {
            return new TmfStateInterval(start, end, quark, value.getAsLong());
        } else if (typeClass.isAssignableFrom(Double.class)) {
            return new TmfStateInterval(start, end, quark, value.getAsDouble());
        } else if (typeClass.isAssignableFrom(String.class)) {
            return new TmfStateInterval(start, end, quark, value.getAsString());
        }
    } catch (ClassNotFoundException e) {
        // Fall through
    }
    // last ditch attempt
    return new TmfStateInterval(start, end, quark, value.toString());
}
 
Example 9
Source File: StorageEntryMapDeserializer.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
private Map<String, StorageEntry> readOuterMap(JsonObject obj, JsonDeserializationContext context) {
    Map<String, StorageEntry> map = new ConcurrentHashMap<>();
    for (Map.Entry<String, JsonElement> me : obj.entrySet()) {
        String key = me.getKey();
        JsonObject value = me.getValue().getAsJsonObject();
        StorageEntry innerMap = new StorageEntry(value.get(JsonStorage.CLASS).getAsString(),
                value.get(JsonStorage.VALUE));
        map.put(key, innerMap);
    }
    return map;
}
 
Example 10
Source File: JsonStringToJsonIntermediateConverter.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Parses a provided JsonObject input using the provided JsonArray schema into
 * a JsonObject.
 * @param record
 * @param schema
 * @return
 * @throws DataConversionException
 */
private JsonObject parse(JsonObject record, JsonSchema schema)
    throws DataConversionException {
    JsonObject output = new JsonObject();
    for (int i = 0; i < schema.fieldsCount(); i++) {
      JsonSchema schemaElement = schema.getFieldSchemaAt(i);
      String columnKey = schemaElement.getColumnName();
      JsonElement parsed;
      if (!record.has(columnKey)) {
        output.add(columnKey, JsonNull.INSTANCE);
        continue;
      }

      JsonElement columnValue = record.get(columnKey);
      switch (schemaElement.getType()) {
        case UNION:
          parsed = parseUnionType(schemaElement, columnValue);
          break;
        case ENUM:
          parsed = parseEnumType(schemaElement, columnValue);
          break;
        default:
          if (columnValue.isJsonArray()) {
            parsed = parseJsonArrayType(schemaElement, columnValue);
          } else if (columnValue.isJsonObject()) {
            parsed = parseJsonObjectType(schemaElement, columnValue);
          } else {
            parsed = parsePrimitiveType(schemaElement, columnValue);
          }
      }
      output.add(columnKey, parsed);
    }
    return output;
}
 
Example 11
Source File: BrewerySearchResultDeserializer.java    From ratebeer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public BrewerySearchResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
	JsonObject object = json.getAsJsonObject();
	BrewerySearchResult brewerySearchResult = new BrewerySearchResult();

	brewerySearchResult.brewerId = object.get("BrewerID").getAsInt();
	brewerySearchResult.brewerName = Normalizer.get().cleanHtml(object.get("BrewerName").getAsString());
	brewerySearchResult.city = Normalizer.get().cleanHtml(object.get("BrewerCity").getAsString());
	brewerySearchResult.countryId = object.get("CountryID").getAsInt();
	if (object.has("StateID") && !(object.get("StateID") instanceof JsonNull))
		brewerySearchResult.stateId = object.get("StateID").getAsInt();

	return brewerySearchResult;
}
 
Example 12
Source File: FAQRespositoryImpl.java    From pacbot with Apache License 2.0 5 votes vote down vote up
@Override
public List<Map<String, Object>> getRelevantFAQSFromEs(String widgetId,
        String domainId, List<String> tag, List<String> faqid,
        List<Map<String, Object>> releventfaqs) throws DataException {
    // Get All FAQ's assigned to to this widgetId from ES.
    JsonParser jsonParser = new JsonParser();
    StringBuilder urlToQueryBuffer = new StringBuilder(esUrl).append("/")
            .append("faqs/faqinfo").append("/").append("_search");
    StringBuilder requestFaqBody = new StringBuilder(
            "{\"_source\":[\"faqname\",\"answer\"],\"query\":{\"bool\":{\"must\":[{\"terms\":{\"tag.keyword\":"
                    + tag
                    + "}},{\"match\":{\"domainid.keyword\":\""
                    + domainId
                    + "\"}}],\"must_not\":[{\"terms\":{\"faqid.keyword\":"
                    + faqid + "}}]}}}");
    String responseFaqJson ;
   try{
       responseFaqJson= PacHttpUtils.doHttpPost(

            urlToQueryBuffer.toString(), requestFaqBody.toString());
   }catch(Exception e){
       throw new DataException(e);
   }
    JsonObject resultFaqJson = (JsonObject) jsonParser
            .parse(responseFaqJson);
    JsonObject hitsFaq = (JsonObject) resultFaqJson.get("hits");
    JsonArray jsonArrayFaq = hitsFaq.get("hits").getAsJsonArray();
    for (int j = 0; j < jsonArrayFaq.size(); j++) {
        JsonObject sourceFaq = (JsonObject) jsonArrayFaq.get(j)
                .getAsJsonObject().get("_source");
        ConcurrentHashMap<String, Object> relectfaqDetails = new ConcurrentHashMap<>();
        relectfaqDetails.put("faqName", sourceFaq.get("faqname")
                .getAsString());
        relectfaqDetails.put("faqAnswer", sourceFaq.get("answer")
                .getAsString());
        releventfaqs.add(relectfaqDetails);

    }
    return releventfaqs;
}
 
Example 13
Source File: JsonParser.java    From Ouroboros with GNU General Public License v3.0 4 votes vote down vote up
public String getCatalogFilename(JsonObject catalogThreadJson){
    JsonElement fileName = catalogThreadJson.get(CATALOG_FILENAME);
    return fileName != null ? fileName.getAsString() : null;
}
 
Example 14
Source File: ASTSignatureDeserializer.java    From steady with Apache License 2.0 4 votes vote down vote up
private Node getNodeChildElement(JsonObject jsonObject){

	   String fValue = jsonObject.get(VALUE).getAsString();				//Retrieve the Value
	   String strLabel = jsonObject.get(ENTITY_TYPE).getAsString();
	   EntityType fLabel = ASTUtil.getJavaEntityType(strLabel); 									//Retrieve the EntityType

	    //Instantiate the Node object here
	    Node childNode = new Node(fLabel,fValue);

     	//Retrieve the SourceCodeEntity
	    SourceCodeEntity srcCodeEntity = null;
	    JsonObject srcCodeEntityJsonObject = jsonObject.get(SOURCE_CODE_ENTITY).getAsJsonObject();
	    int modifiers = srcCodeEntityJsonObject.get(SRC_ENTITY_MODIFIERS).getAsInt();

	    //SourceRange JsonObject
	    JsonObject srcCodeEntitySrcRangeJsonObject = srcCodeEntityJsonObject.get(SRC_ENTITY_SOURCE_RANGE).getAsJsonObject();
	    int srcRangeStart = srcCodeEntitySrcRangeJsonObject.get(SRC_ENTITY_SOURCE_RANGE_START).getAsInt();
	    int srcRangeEnd = srcCodeEntitySrcRangeJsonObject.get(SRC_ENTITY_SOURCE_RANGE_END).getAsInt();
	    SourceRange srcRange = new SourceRange(srcRangeStart,srcRangeEnd);
	    srcCodeEntity =  new SourceCodeEntity(fValue,fLabel,modifiers,srcRange);

	    JsonElement jsonChildrenElement = jsonObject.get(CHILDREN);
		if(jsonChildrenElement != null){

				JsonArray jsonChildrenArray = jsonChildrenElement.getAsJsonArray();

			 	//Add the children of a Node
				final Node [] children = new Node[jsonChildrenArray.size()];

				for (int i=0; i < children.length; i++){
					final JsonObject jsonChildren = jsonChildrenArray.get(i).getAsJsonObject();

					//Get the child Node element and add it
					Node newChild = getNodeChildElement(jsonChildren);
					childNode.add(newChild);
				}

		}

	    childNode.setEntity(srcCodeEntity);
	    return childNode;
  }
 
Example 15
Source File: JsonParser.java    From Ouroboros with GNU General Public License v3.0 4 votes vote down vote up
public String getThreadSub(JsonObject threadJson){
    JsonElement sub = threadJson.get(THREAD_SUB);
    return sub != null ? sub.getAsString() : null;
}
 
Example 16
Source File: JsonRpcResponseGsonAdaptor.java    From swellrt with Apache License 2.0 4 votes vote down vote up
@Override
public JsonRpcResponse deserialize(JsonElement json, Type type,
    JsonDeserializationContext context) throws JsonParseException {
  JsonObject jsonObject = json.getAsJsonObject();

  String id = jsonObject.get(ResponseProperty.ID.key()).getAsString();
  if (jsonObject.has(ResponseProperty.ERROR.key())) {
    JsonElement errorObject = jsonObject.get(ResponseProperty.ERROR.key());
    String errorMessage = errorObject.getAsJsonObject().get("message").getAsString();
    return JsonRpcResponse.error(id, errorMessage);
  }

  // Deserialize the data.
  Map<ParamsProperty, Object> properties = new HashMap<ParamsProperty, Object>();
  JsonElement data = jsonObject.get(ResponseProperty.DATA.key());
  if (data != null && data.isJsonObject()) {
    for (Entry<String, JsonElement> parameter : data.getAsJsonObject().entrySet()) {
      ParamsProperty parameterType = ParamsProperty.fromKey(parameter.getKey());
      if (parameterType == null) {
        // Skip this unknown parameter.
        continue;
      }
      Object object = null;
      if (parameterType == ParamsProperty.BLIPS) {
        object = context.deserialize(parameter.getValue(), GsonFactory.BLIP_MAP_TYPE);
      } else if (parameterType == ParamsProperty.PARTICIPANTS_ADDED ||
          parameterType == ParamsProperty.PARTICIPANTS_REMOVED) {
        object = context.deserialize(parameter.getValue(), GsonFactory.PARTICIPANT_LIST_TYPE);
      } else if (parameterType == ParamsProperty.THREADS) {
        object = context.deserialize(parameter.getValue(), GsonFactory.THREAD_MAP_TYPE);
      } else if (parameterType == ParamsProperty.WAVELET_IDS) {
        object = context.deserialize(parameter.getValue(), GsonFactory.WAVELET_ID_LIST_TYPE);
      } else if (parameterType == ParamsProperty.RAW_DELTAS) {
        object = context.deserialize(parameter.getValue(), GsonFactory.RAW_DELTAS_TYPE);
      } else {
        object = context.deserialize(parameter.getValue(), parameterType.clazz());
      }
      properties.put(parameterType, object);
    }
  }

  return JsonRpcResponse.result(id, properties);
}
 
Example 17
Source File: GsonProvider.java    From JsonSurfer with MIT License 4 votes vote down vote up
@Override
public Object resolve(JsonObject object, String key) {
    return object.get(key);
}
 
Example 18
Source File: FileManager.java    From Happy_MinecraftClient with GNU General Public License v3.0 4 votes vote down vote up
public void loadModules() throws IOException {
    if(!modules.exists()) {
        modules.createNewFile();
        saveModules();
        return;
    }

    final BufferedReader bufferedReader = new BufferedReader(new FileReader(modules));

    final JsonElement jsonElement = gson.fromJson(bufferedReader, JsonElement.class);

    if(jsonElement instanceof JsonNull)
        return;

    final JsonObject jsonObject = (JsonObject) jsonElement;

    for(final Module module : ModuleManager.getModules()) {
        if(!jsonObject.has(module.getModuleName()))
            continue;

        final JsonElement moduleElement = jsonObject.get(module.getModuleName());

        if(moduleElement instanceof JsonNull)
            continue;

        final JsonObject moduleJson = (JsonObject) moduleElement;

        if(moduleJson.has("state"))
            module.setState(moduleJson.get("state").getAsBoolean());
        if(moduleJson.has("key"))
         module.setKeyBind(moduleJson.get("key").getAsInt());

        for(final Value value : module.getValues()) {
            if(!moduleJson.has(value.getValueName()))
                continue;

            if(value.getObject() instanceof Float)
                value.setObject(moduleJson.get(value.getValueName()).getAsFloat());
            else if(value.getObject() instanceof Double)
                value.setObject(moduleJson.get(value.getValueName()).getAsDouble());
            else if(value.getObject() instanceof Integer)
                value.setObject(moduleJson.get(value.getValueName()).getAsInt());
            else if(value.getObject() instanceof Long)
                value.setObject(moduleJson.get(value.getValueName()).getAsLong());
            else if(value.getObject() instanceof Byte)
                value.setObject(moduleJson.get(value.getValueName()).getAsByte());
            else if(value.getObject() instanceof Boolean)
                value.setObject(moduleJson.get(value.getValueName()).getAsBoolean());
            else if(value.getObject() instanceof String)
                value.setObject(moduleJson.get(value.getValueName()).getAsString());
        }
    }
}
 
Example 19
Source File: VulnerabilityRepository.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * Gets the trend annotations.
 *
 * @param ag
 *            the ag
 * @param from
 *            the from
 * @return the trend annotations
 */
public List<Map<String, Object>> getTrendAnnotations(String ag, Date from) {

	List<Map<String, Object>> notes = new ArrayList<>();
	SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");

	StringBuilder urlToQuery = new StringBuilder(esUrl).append("/")
			.append("assetgroup_annotations/annotations/_search");
	StringBuilder requestBody = new StringBuilder(
			"{\"size\":10000,\"query\":{\"bool\":{\"must\":[{\"range\":{\"date\":{\"gte\":\"");
	requestBody.append(dateformat.format(from));
	requestBody.append("\",\"lte\":\"");
	requestBody.append(dateformat.format(new Date()));
	requestBody.append("\",\"format\":\"yyyy-MM-dd\"}}}");
	requestBody.append(",{\"terms\":{\"ag.keyword\":[\"\",\"");
	requestBody.append(ag).append("\"]}}]}}}");

	String responseJson = "";
	try {
		responseJson = PacHttpUtils.doHttpPost(urlToQuery.toString(), requestBody.toString());
	} catch (Exception e) {
		LOGGER.error("Error in getTrendAnnotations from ES", e);
	}
	JsonParser jsonParser = new JsonParser();
	if (StringUtils.isNotEmpty(responseJson)) {
		JsonObject resultJson = (JsonObject) jsonParser.parse(responseJson);
		JsonArray hits = resultJson.get("hits").getAsJsonObject().get("hits").getAsJsonArray();
		Map<String, Object> note;
		if (hits.size() > 0) {
			for (int i = 0; i < hits.size(); i++) {
				JsonObject obj = (JsonObject) hits.get(i);
				JsonObject sourceJson = (JsonObject) obj.get("_source");
				if (sourceJson != null) {
					note = new Gson().fromJson(sourceJson, new TypeToken<Map<String, Object>>() {
					}.getType());
					notes.add(note);
				}
			}
		}
	}
	return notes;
}
 
Example 20
Source File: FindingsFormat20.java    From elexis-3-core with Eclipse Public License 1.0 4 votes vote down vote up
public int isFindingsFormat(String rawContent) {
	JsonObject jsonObject = getJsonObject(rawContent);
	JsonElement resourceType = jsonObject.get("resourceType");
	
	return checkFindingsFormatProperties(resourceType, jsonObject);
}