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

The following examples show how to use com.google.gson.JsonObject#entrySet() . 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: DsAPIImpl.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Map<String, String> getDSID(String token) {
    String response = transport.execute(SimpleRequestBuilder.buildNewJsonRequest(ClassKeys.SYSTEM)
            .addFunction(FunctionKeys.GET_DSID).addParameter(ParameterKeys.TOKEN, token).buildRequestString());
    JsonObject responseObj = JSONResponseHandler.toJsonObject(response);

    if (JSONResponseHandler.checkResponse(responseObj)) {
        JsonObject obj = JSONResponseHandler.getResultJsonObject(responseObj);
        if (obj != null) {
            Map<String, String> dsidMap = new HashMap<String, String>(obj.entrySet().size());
            for (Entry<String, JsonElement> entry : obj.entrySet()) {
                dsidMap.put(entry.getKey(), entry.getValue().getAsString());
            }
            return dsidMap;
        }
    }
    return null;
}
 
Example 2
Source File: ConfigurationDeserializer.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private Configuration deserialize(JsonObject propertiesObject) {
    Configuration configuration = new Configuration();
    for (Entry<String, JsonElement> entry : propertiesObject.entrySet()) {
        JsonElement value = entry.getValue();
        String key = entry.getKey();
        if (value.isJsonPrimitive()) {
            JsonPrimitive primitive = value.getAsJsonPrimitive();
            configuration.put(key, deserialize(primitive));
        } else if (value.isJsonArray()) {
            JsonArray array = value.getAsJsonArray();
            configuration.put(key, deserialize(array));
        } else {
            throw new IllegalArgumentException(
                    "Configuration parameters must be primitives or arrays of primities only but was " + value);
        }
    }
    return configuration;
}
 
Example 3
Source File: JsonUtil.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
public static Map<String, JsonElement> getNullableMapKey(JsonObject obj, String key)
        throws ResponseFormatException {
    Map<String, JsonElement> ret = new HashMap<>();
    JsonElement el = getNullableKey(obj, key);
    if (el == null) {
        return ret;
    }
    if (! el.isJsonObject()) {
        throw new ResponseFormatException(key, el);
    }
    JsonObject jo = el.getAsJsonObject();
    for (Map.Entry<String, JsonElement> entry : jo.entrySet()) {
        ret.put(entry.getKey(), entry.getValue());
    }
    return ret;
}
 
Example 4
Source File: VariantSelectorData.java    From OpenModsLib with MIT License 6 votes vote down vote up
@Override
public VariantSelectorData deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
	final JsonObject jsonObject = json.getAsJsonObject();
	final Map<String, Matcher> matchers = Maps.newHashMap();
	final Set<ResourceLocation> allModels = Sets.newHashSet();

	for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
		final String name = e.getKey();
		final JsonElement value = e.getValue();

		final Matcher matcher;
		if (value.isJsonObject()) {
			matcher = createKeyedMatcher(name, e.getValue().getAsJsonObject());
		} else {
			matcher = createUnconditionalMatcher(name, e.getValue());
		}

		allModels.addAll(matcher.getAllModels());
		matchers.put(name, matcher);
	}

	final VariantSelectorData result = new VariantSelectorData();
	result.allModels = ImmutableSet.copyOf(allModels);
	result.matchers = ImmutableMap.copyOf(matchers);
	return result;
}
 
Example 5
Source File: BlockRegistry.java    From tectonicus with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Map<String, String> populateTextureMap(Map<String, String> textureMap, JsonObject textures) throws JsonSyntaxException
{
	Map<String, String> newTexMap = new HashMap<>();
	
	Set<Entry<String, JsonElement>> entrySet = textures.entrySet();
	for(Map.Entry<String,JsonElement> e : entrySet)
	{
		String key = e.getKey();
		StringBuilder tex = new StringBuilder(textures.get(key).getAsString());
		
		if(tex.charAt(0) == '#')
	    {
	    	newTexMap.put(key, textureMap.get(tex.deleteCharAt(0).toString()));
	    }
	    else
	    {
	    	newTexMap.put(key, tex.toString());
	    }
	}
	
	return newTexMap;
}
 
Example 6
Source File: BiremeUtility.java    From bireme with Apache License 2.0 6 votes vote down vote up
/**
 * Given the key, return the json value as String, ignoring case considerations.
 * @param data the JsonObject
 * @param fieldName the key
 * @return the value as String
 * @throws BiremeException when the JsonObject doesn't have the key
 */
public static String jsonGetIgnoreCase(JsonObject data, String fieldName) throws BiremeException {
  JsonElement element = data.get(fieldName);

  if (element == null) {
    for (Entry<String, JsonElement> iter : data.entrySet()) {
      String key = iter.getKey();

      if (key.equalsIgnoreCase(fieldName)) {
        element = iter.getValue();
        break;
      }
    }
  }

  if (element == null) {
    throw new BiremeException(
        "Not found. Record does not have a field named \"" + fieldName + "\".\n");
  }

  if (element.isJsonNull()) {
    return null;
  } else {
    return element.getAsString();
  }
}
 
Example 7
Source File: JsonTreeTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testToJsonTree() {
  BagOfPrimitives bag = new BagOfPrimitives(10L, 5, false, "foo");
  JsonElement json = gson.toJsonTree(bag);
  assertTrue(json.isJsonObject());
  JsonObject obj = json.getAsJsonObject();
  Set<Entry<String, JsonElement>> children = obj.entrySet();
  assertEquals(4, children.size());
  assertContains(obj, new JsonPrimitive(10L));
  assertContains(obj, new JsonPrimitive(5));
  assertContains(obj, new JsonPrimitive(false));
  assertContains(obj, new JsonPrimitive("foo"));
}
 
Example 8
Source File: FieldDeserializer.java    From ha-bridge with Apache License 2.0 5 votes vote down vote up
@Override
public Field deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx)
{
    JsonObject obj = json.getAsJsonObject();
    String theKey;

    fields = new HashMap<String, JsonElement>();
    for(Entry<String, JsonElement> entry:obj.entrySet()){
    	theKey = entry.getKey();
        JsonElement theRawDetail = obj.get(theKey);
        fields.put(theKey, theRawDetail);
    }
    
    return new Field(fields);
}
 
Example 9
Source File: Generated.java    From graphql_java_gen with MIT License 5 votes vote down vote up
public UnknownEntry(JsonObject fields) throws SchemaViolationError {
    for (Map.Entry<String, JsonElement> field : fields.entrySet()) {
        String key = field.getKey();
        String fieldName = getFieldName(key);
        switch (fieldName) {
            case "key": {
                responseData.put(key, jsonAsString(field.getValue(), key));

                break;
            }

            case "ttl": {
                LocalDateTime optional1 = null;
                if (!field.getValue().isJsonNull()) {
                    optional1 = LocalDateTime.parse(jsonAsString(field.getValue(), key));
                }

                responseData.put(key, optional1);

                break;
            }

            case "__typename": {
                responseData.put(key, jsonAsString(field.getValue(), key));
                break;
            }
            default: {
                throw new SchemaViolationError(this, key, field.getValue());
            }
        }
    }
}
 
Example 10
Source File: SettingsFile.java    From Wurst7 with GNU General Public License v3.0 5 votes vote down vote up
private void loadSettings(Feature feature, JsonObject json)
{
	Map<String, Setting> settings = feature.getSettings();
	
	for(Entry<String, JsonElement> e : json.entrySet())
	{
		String key = e.getKey().toLowerCase();
		if(!settings.containsKey(key))
			continue;
		
		settings.get(key).fromJson(e.getValue());
	}
}
 
Example 11
Source File: MediaLinkAdapter.java    From activitystreams with Apache License 2.0 5 votes vote down vote up
public MediaLink deserialize(
  JsonElement json, 
  Type typeOfT,
  JsonDeserializationContext context) 
    throws JsonParseException {
  
  checkArgument(json.isJsonObject());
  JsonObject obj = (JsonObject) json;
  MediaLink.Builder builder = 
    LegacyMakers.mediaLink();
  for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
    String name = entry.getKey();
    JsonElement val = entry.getValue();
    if (val.isJsonPrimitive())
      builder.set(
        name,
        primConverter.convert(val.getAsJsonPrimitive()));
    else if (val.isJsonArray())        
      builder.set(
        name, 
        context.deserialize(val, Iterable.class));
    else if (val.isJsonObject())
      builder.set(
        name, 
        context.deserialize(
          val, 
          ASObject.class));
  }
  return builder.get();
}
 
Example 12
Source File: JsonDeserializationData.java    From Diorite with MIT License 5 votes vote down vote up
@Override
public <T, C extends Collection<T>> void getAsCollection(String key, Class<T> type, C collection)
{
    JsonElement element = this.getElement(this.element, key);
    if (element == null)
    {
        throw new DeserializationException(type, this, "Can't find valid value for key: " + key);
    }
    if (element.isJsonArray())
    {
        JsonArray jsonArray = element.getAsJsonArray();
        for (JsonElement jsonElement : jsonArray)
        {
            collection.add(this.deserializeSpecial(type, jsonElement, null));
        }
    }
    else if (element.isJsonObject())
    {
        JsonObject jsonObject = element.getAsJsonObject();
        for (Entry<String, JsonElement> entry : jsonObject.entrySet())
        {
            collection.add(this.deserializeSpecial(type, entry.getValue(), null));
        }
    }
    else
    {
        throw new DeserializationException(type, this, "Can't find valid value for key: " + key);
    }
}
 
Example 13
Source File: StorageEntryMapDeserializer.java    From smarthome 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 14
Source File: SOARPlugin.java    From cst with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void buildWmeInputTreeFromJson(JsonObject json, Identifier id) {
    Set<Map.Entry<String, JsonElement>> entryset = json.entrySet();
    Entry<String, JsonElement> entry;
    Object value;
    Iterator<Entry<String, JsonElement>> itr = entryset.iterator();
    while (itr.hasNext()) {
        entry = itr.next();
        String key = entry.getKey();
        if (entry.getValue().isJsonPrimitive()) {
            if (entry.getValue().getAsJsonPrimitive().isNumber()) {
                value = (double) entry.getValue().getAsJsonPrimitive().getAsDouble();
                createFloatWME(id, key, (double) value);
            } else if (entry.getValue().getAsJsonPrimitive().isString()) {
                value = (String) entry.getValue().getAsJsonPrimitive().getAsString();
                createStringWME(id, key, (String) value);
            } else if (entry.getValue().getAsJsonPrimitive().isBoolean()) {
                value = (Boolean) entry.getValue().getAsJsonPrimitive().getAsBoolean();
                createStringWME(id, key, value.toString());
            }
        } else if (entry.getValue().isJsonObject()) {
            Identifier newID = createIdWME(id, key);
            if (entry.getValue().getAsJsonObject().size() == 0) {
                continue;
            }
            buildWmeInputTreeFromJson(entry.getValue().getAsJsonObject(), newID);
        }
    }
}
 
Example 15
Source File: MappingDataLoader.java    From ViaVersion with MIT License 5 votes vote down vote up
public static void mapIdentifiers(short[] output, JsonObject oldIdentifiers, JsonObject newIdentifiers, JsonObject diffIdentifiers) {
    for (Map.Entry<String, JsonElement> entry : oldIdentifiers.entrySet()) {
        Map.Entry<String, JsonElement> value = mapIdentifierEntry(entry, oldIdentifiers, newIdentifiers, diffIdentifiers);
        if (value != null) {
            output[Integer.parseInt(entry.getKey())] = Short.parseShort(value.getKey());
        }
    }
}
 
Example 16
Source File: MobileServiceTableBase.java    From azure-mobile-apps-android-client with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param instance Target JsonObject
 * @return List of entities
 */
public static EnumSet<MobileServiceSystemProperty> getSystemProperties(JsonObject instance) {
    EnumSet<MobileServiceSystemProperty> systemProperties = EnumSet.noneOf(MobileServiceSystemProperty.class);

    for (Entry<String, JsonElement> property : instance.entrySet()) {
        String propertyName = property.getKey().trim().toLowerCase(Locale.getDefault());

        switch (propertyName) {
            case MobileServiceSystemColumns.CreatedAt:
                systemProperties.add(MobileServiceSystemProperty.CreatedAt);
                break;
            case MobileServiceSystemColumns.UpdatedAt:
                systemProperties.add(MobileServiceSystemProperty.UpdatedAt);
                break;
            case MobileServiceSystemColumns.Version:
                systemProperties.add(MobileServiceSystemProperty.Version);
                break;
            case MobileServiceSystemColumns.Deleted:
                systemProperties.add(MobileServiceSystemProperty.Deleted);
                break;
            default:
                break;
        }
    }

    return systemProperties;
}
 
Example 17
Source File: GSONUtils.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
/**
 * Function to convert from GSON object model to generic map model.
 *
 * @param jsonElement gson object to transform
 * @return
 */
public static Map gsonJsonObjectToMap(JsonElement jsonElement) {
    Map<String, Object> gsonMap = new LinkedHashMap<>();

    if (jsonElement.isJsonObject()) {
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();

        for (Map.Entry<String, JsonElement> entry : entrySet) {
            if (entry.getValue().isJsonPrimitive()) {
                JsonPrimitive jsonPrimitive = entry.getValue().getAsJsonPrimitive();

                if (jsonPrimitive.isString()) {
                    gsonMap.put(entry.getKey(), jsonPrimitive.getAsString());
                } else if (jsonPrimitive.isBoolean()) {
                    gsonMap.put(entry.getKey(), jsonPrimitive.getAsBoolean());
                } else if (jsonPrimitive.isNumber()) {
                    gsonMap.put(entry.getKey(), jsonPrimitive.getAsNumber());
                } else {
                    //unknown type
                    log.warn("Unknown JsonPrimitive type found : " + jsonPrimitive.toString());
                }
            } else if (entry.getValue().isJsonObject()) {
                gsonMap.put(entry.getKey(), gsonJsonObjectToMap(entry.getValue()));

            } else if (entry.getValue().isJsonArray()) {
                gsonMap.put(entry.getKey(), gsonJsonArrayToObjectArray(entry.getValue().getAsJsonArray()));

            } else {
                // remaining JsonNull type
                gsonMap.put(entry.getKey(), null);

            }
        }
    } else {
        //Not a JsonObject hence return empty map
        log.error("Provided gson model does not represent json object");
    }

    return gsonMap;
}
 
Example 18
Source File: FqdnExecutor.java    From oneops with Apache License 2.0 4 votes vote down vote up
private List<HealthCheck> healthChecks(Context context, String logKey) {
  Instance lb = context.lb;
  if (lb == null) {
    throw new RuntimeException("DependsOn Lb is empty");
  }
  List<HealthCheck> hcList = new ArrayList<>();
  String listenerJson = lb.getCiAttributes().get(ATTRIBUTE_LISTENERS);
  String ecvMapJson = lb.getCiAttributes().get(ATTRIBUTE_ECV_MAP);
  if (isNotBlank(listenerJson) && isNotBlank(ecvMapJson)) {
    JsonElement element = jsonParser.parse(ecvMapJson);
    if (element instanceof JsonObject) {
      JsonObject root = (JsonObject) element;
      Set<Entry<String, JsonElement>> set = root.entrySet();
      Map<Integer, String> ecvMap = set.stream().
          collect(Collectors.toMap(s -> Integer.parseInt(s.getKey()), s -> s.getValue().getAsString()));
      logger.info(logKey + "listeners "  + listenerJson);
      JsonArray listeners = (JsonArray) jsonParser.parse(listenerJson);
      listeners.forEach(s -> {
        String listener = s.getAsString();
        //listeners are generally in this format 'http <lb-port> http <app-port>', gslb needs to use the lb-port for health checks
        //ecv map is configured as '<app-port> : <ecv-url>', so we need to use the app-port from listener configuration to lookup the ecv config from ecv map
        String[] config = listener.split(" ");
        if (config.length >= 2) {
          String protocol = config[0];
          int lbPort = Integer.parseInt(config[1]);
          int ecvPort = Integer.parseInt(config[config.length-1]);
          String healthConfig = ecvMap.get(ecvPort);
          if (healthConfig != null) {
            if ((protocol.equals("http"))) {
              String path = healthConfig.substring(healthConfig.indexOf(" ")+1);
              logger.info(logKey +  "healthConfig : " + healthConfig + ", health check configuration, protocol: " + protocol + ", port: " + lbPort
                  + ", path " + path);
              hcList.add(newHealthCheck(protocol, lbPort, path));
            } else {
              logger.info(logKey + "health check configuration, protocol: " + protocol + ", port: " + lbPort);
              hcList.add(newHealthCheck(protocol, lbPort, null ));
            }
          }
        }
      });
    }
  }
  return hcList;
}
 
Example 19
Source File: SQLiteLocalStore.java    From azure-mobile-apps-android-client with Apache License 2.0 4 votes vote down vote up
private Statement generateUpsertStatement(String tableName, JsonObject[] items, boolean fromServer) {
    Statement result = new Statement();

    String invTableName = normalizeTableName(tableName);

    StringBuilder sql = new StringBuilder();

    sql.append("INSERT OR REPLACE INTO \"");
    sql.append(invTableName);
    sql.append("\" (");

    String delimiter = "";

    JsonObject firstItem = items[0];

    Map<String, ColumnDataInfo> tableDefinition = mTables.get(invTableName);

    List<Object> parameters = new ArrayList<Object>(firstItem.entrySet().size());

    int columnsOnStatement = 0;

    for (Entry<String, JsonElement> property : firstItem.entrySet()) {

        //if (isSystemProperty(property.getKey()) && !tableDefinition.containsKey(property.getKey())) {
        //    continue;
        //}

        if (fromServer && !tableDefinition.containsKey(property.getKey().toLowerCase())) {
            continue;
        }

        String invColumnName = normalizeColumnName(property.getKey());
        sql.append(delimiter);
        sql.append("\"");
        sql.append(invColumnName);
        sql.append("\"");
        delimiter = ",";

        columnsOnStatement++;
    }

    if (columnsOnStatement == 0){
        result.sql = "";
        result.parameters = parameters;

        return result;
    }

    sql.append(") VALUES ");

    String prefix = "";

    for (JsonObject item : items) {
        sql.append(prefix);
        appendInsertValuesSql(sql, parameters, tableDefinition, item, fromServer);
        prefix = ",";
    }

    result.sql = sql.toString();
    result.parameters = parameters;

    return result;
}
 
Example 20
Source File: GsonUtilities.java    From streamsx.topology with Apache License 2.0 3 votes vote down vote up
/**
 * Add all the properties in the {@code source} JSON object into {@code target} JSON object. Existing properties will be overridden.
 * <p>
 * E.g. if {@code target} contains:
 * <pre><code>
 * 		{ "t1": {}, "t2": {} }
 * </code></pre>
 * and {@code source} contains:
 * <pre><code>
 * 		{ "s1": {}, "s2": {}, "s3": {} }
 * </code></pre>
 * then {@code target} after the call, contains:
 * <pre><code>
 * 		{ "t1": {}, "t2": {}, "s1": {}, "s2": {}, "s3": {} }
 * </code></pre>
 * 
 * @param target JSON object to copy properties to
 * @param source JSON object to receive properties from
 * @return modified target JSON object
 */
public static JsonObject addAll(JsonObject target, JsonObject source) {
	for (Entry<String, JsonElement> entry : source.entrySet()) {
		target.add(entry.getKey(), entry.getValue());
    }
	return target;
}