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

The following examples show how to use com.google.gson.JsonElement#isJsonArray() . 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: JsonUtils.java    From ProtocolSupport with GNU Affero General Public License v3.0 6 votes vote down vote up
private static String toString(JsonElement jsonElement) {
	String abbreviateMiddle = String.valueOf(jsonElement);
	if (jsonElement == null) {
		return "null (missing)";
	}
	if (jsonElement.isJsonNull()) {
		return "null (json)";
	}
	if (jsonElement.isJsonArray()) {
		return "an array (" + abbreviateMiddle + ")";
	}
	if (jsonElement.isJsonObject()) {
		return "an object (" + abbreviateMiddle + ")";
	}
	if (jsonElement.isJsonPrimitive()) {
		JsonPrimitive asJsonPrimitive = jsonElement.getAsJsonPrimitive();
		if (asJsonPrimitive.isNumber()) {
			return "a number (" + abbreviateMiddle + ")";
		}
		if (asJsonPrimitive.isBoolean()) {
			return "a boolean (" + abbreviateMiddle + ")";
		}
	}
	return abbreviateMiddle;
}
 
Example 2
Source File: FriendlyPingServer.java    From friendlyping with Apache License 2.0 6 votes vote down vote up
/**
 * Send client list to newly registered client. When a new client is registered, that client must
 * be informed about the other registered clients.
 *
 * @param client Newly registered client.
 */
private void sendClientList(Client client) {
  ArrayList<Client> clientList = new ArrayList();
  for (Entry<String, Client> clientEntry : clientMap.entrySet()) {
    Client currentClient = clientEntry.getValue();
    if (currentClient.registrationToken != client.registrationToken) {
      clientList.add(currentClient);
    }
  }
  JsonElement clientElements = gson.toJsonTree(clientList,
      new TypeToken<Collection<Client>>() {}.getType());
  if (clientElements.isJsonArray()) {
    JsonObject jSendClientList = new JsonObject();

    JsonObject jData = new JsonObject();
    jData.addProperty(ACTION_KEY, SEND_CLIENT_LIST);
    jData.add(CLIENTS_KEY, clientElements);

    jSendClientList.add(DATA_KEY, jData);
    friendlyGcmServer.send(client.registrationToken, jSendClientList);
  }
}
 
Example 3
Source File: AllocatedGroupRangeDbMigrator.java    From Android-nRF-Mesh-Library with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public List<AllocatedGroupRange> deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
    final List<AllocatedGroupRange> groupRanges = new ArrayList<>();
    try {
        if(json.isJsonArray()) {
            final JsonArray jsonObject = json.getAsJsonArray();
            for (int i = 0; i < jsonObject.size(); i++) {
                final JsonObject unicastRangeJson = jsonObject.get(i).getAsJsonObject();
                final int lowAddress = unicastRangeJson.get("lowAddress").getAsInt();
                final int highAddress = unicastRangeJson.get("highAddress").getAsInt();
                groupRanges.add(new AllocatedGroupRange(lowAddress, highAddress));
            }
        }
    } catch (Exception ex) {
        Log.e(TAG, "Error while de-serializing Allocated group range: " + ex.getMessage());
    }
    return groupRanges;
}
 
Example 4
Source File: FixedChatSerializer.java    From Carbon-2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static String toString(JsonElement jsonElement) {
    String string = StringUtils.abbreviateMiddle(String.valueOf(jsonElement), "...", 10);
    if (jsonElement == null) {
        return "null (missing)";
    }
    if (jsonElement.isJsonNull()) {
        return "null (json)";
    }
    if (jsonElement.isJsonArray()) {
        return "an array (" + string + ")";
    }
    if (jsonElement.isJsonObject()) {
        return "an object (" + string + ")";
    }
    if (!jsonElement.isJsonPrimitive()) {
        return string;
    }
    JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
    if (jsonPrimitive.isNumber()) {
        return "a number (" + string + ")";
    }
    if (!jsonPrimitive.isBoolean()) {
        return string;
    }
    return "a boolean (" + string + ")";
}
 
Example 5
Source File: AbstractFeatureSerializer.java    From quaerite with Apache License 2.0 6 votes vote down vote up
static List<String> toStringList(JsonElement stringArr) {
    if (stringArr == null) {
        return Collections.EMPTY_LIST;
    } else if (stringArr.isJsonPrimitive()) {
        return Collections.singletonList(stringArr.getAsString());
    } else if (stringArr.isJsonArray()) {
        List<String> ret = new ArrayList<>();
        for (JsonElement el : ((JsonArray)stringArr)) {
            if (! el.isJsonNull()) {
                ret.add(el.getAsJsonPrimitive().getAsString());
            }
        }
        return ret;
    } else {
        throw new IllegalArgumentException("Didn't expect json object here:" + stringArr);
    }
}
 
Example 6
Source File: BackupUtils.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Nullable
public static List<String> getStringArray(JsonObject data, String name) {
   JsonElement elem = data.get(name);
   if (elem == null) {
      return null;
   }

   if (!elem.isJsonArray()) {
      return null;
   }

   List<String> result = new ArrayList<>();
   for (JsonElement e : elem.getAsJsonArray()) {
      result.add(e.getAsString());
   }

   return result;
}
 
Example 7
Source File: JWTDeserializer.java    From JWTDecode.Android with MIT License 6 votes vote down vote up
@SuppressWarnings("SameParameterValue")
private List<String> getStringOrArray(JsonObject obj, String claimName) {
    List<String> list = Collections.emptyList();
    if (obj.has(claimName)) {
        JsonElement arrElement = obj.get(claimName);
        if (arrElement.isJsonArray()) {
            JsonArray jsonArr = arrElement.getAsJsonArray();
            list = new ArrayList<>(jsonArr.size());
            for (int i = 0; i < jsonArr.size(); i++) {
                list.add(jsonArr.get(i).getAsString());
            }
        } else {
            list = Collections.singletonList(arrElement.getAsString());
        }
    }
    return list;
}
 
Example 8
Source File: ActionSimulate.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private List<NameIdPair> readIdentity(JsonElement o) throws Exception {
	List<NameIdPair> results = new ArrayList<>();
	List<String> flags = new ArrayList<>();
	if (o.isJsonArray()) {
		flags = XGsonBuilder.instance().fromJson(o, stringCollectionType);
	} else if (o.isJsonPrimitive() && o.getAsJsonPrimitive().isString()) {
		flags.add(o.getAsJsonPrimitive().getAsString());
	}
	for (String str : flags) {
		NameIdPair p = new NameIdPair(str, str);
		results.add(p);
	}
	return results;
}
 
Example 9
Source File: DungeonSettings.java    From minecraft-roguelike with GNU General Public License v3.0 5 votes vote down vote up
private List<Integer> parseLevels(JsonElement e){
	
	List<Integer> levels = new ArrayList<Integer>();
	
	if(e.isJsonArray()){
		JsonArray arr = e.getAsJsonArray();
		for(JsonElement i : arr){
			levels.add(i.getAsInt());
		}
		return levels;
	}
	
	levels.add(e.getAsInt());
	return levels;
}
 
Example 10
Source File: JsonRecordReader.java    From datawave with Apache License 2.0 5 votes vote down vote up
protected void setupIterator(JsonReader reader) {
    JsonParser parser = new JsonParser();
    JsonElement root = parser.parse(reader);
    
    if (root.isJsonArray()) {
        // Currently positioned to read a set of objects
        jsonIterator = root.getAsJsonArray().iterator();
    } else {
        // Currently positioned to read a single object
        jsonIterator = IteratorUtils.singletonIterator(root);
    }
}
 
Example 11
Source File: OperationQueue.java    From azure-mobile-apps-android-client with Apache License 2.0 5 votes vote down vote up
/**
 * Loads the queue of table operations from the local store
 *
 * @param store the local store
 * @return the queue of table operations
 * @throws java.text.ParseException
 * @throws MobileServiceLocalStoreException
 */
public static OperationQueue load(MobileServiceLocalStore store) throws ParseException, MobileServiceLocalStoreException {
    OperationQueue opQueue = new OperationQueue(store);

    JsonElement operations = store.read(QueryOperations.tableName(OPERATION_QUEUE_TABLE).orderBy("__queueLoadedAt", QueryOrder.Ascending)
            .orderBy("sequence", QueryOrder.Ascending));

    if (operations.isJsonArray()) {
        JsonArray array = (JsonArray) operations;

        for (JsonElement element : array) {
            if (element.isJsonObject()) {
                OperationQueueItem opQueueItem = deserialize((JsonObject) element);
                TableOperation operation = opQueueItem.getOperation();
                opQueue.mQueue.add(opQueueItem);

                // '/' is a reserved character that cannot be used on string
                // ids.
                // We use it to build a unique compound string from
                // tableName and itemId
                String tableItemId = operation.getTableName() + "/" + operation.getItemId();

                opQueue.mIdOperationMap.put(tableItemId, opQueueItem);

                Integer tableCount = opQueue.mTableCountMap.get(operation.getTableName());

                if (tableCount != null) {
                    opQueue.mTableCountMap.put(operation.getTableName(), tableCount + 1);
                } else {
                    opQueue.mTableCountMap.put(operation.getTableName(), 1);
                }
            }
        }
    }

    return opQueue;
}
 
Example 12
Source File: ManifestUtils.java    From Wizardry with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void loadManifestFile(File externalManifest, HashMap<String, HashMap<String, String>> manifestMap, boolean verbose) throws IOException {
	JsonElement element = new JsonParser().parse(new FileReader(externalManifest));

	if (element != null && element.isJsonObject()) {

		for (Map.Entry<String, JsonElement> categorySet : element.getAsJsonObject().entrySet()) {
			String category = categorySet.getKey();
			JsonElement categoryElement = categorySet.getValue();

			manifestMap.putIfAbsent(category, new HashMap<>());
			if( verbose ) {
				Wizardry.LOGGER.info("    >  |");
				Wizardry.LOGGER.info("    >  |_ Category found: " + category);
			}

			if (categoryElement.isJsonArray()) {
				for (JsonElement element1 : categoryElement.getAsJsonArray()) {
					if (!element1.isJsonObject()) continue;

					JsonObject externalObject = element1.getAsJsonObject();

					if (!externalObject.has("id") || !externalObject.has("hash")) continue;

					String id = externalObject.getAsJsonPrimitive("id").getAsString();
					String hash = externalObject.getAsJsonPrimitive("hash").getAsString();

					manifestMap.get(category).put(id, hash);
					if( verbose ) {
						Wizardry.LOGGER.info("    >  | |_ " + id + ": " + hash);
					}
				}
			}
		}
	}
}
 
Example 13
Source File: JsonUtil.java    From UltimateAndroid with Apache License 2.0 5 votes vote down vote up
public static ArrayList getArrayListFromJson(String jsonString) {
    JsonParser jsonParser = new JsonParser();
    Gson gson = new Gson();
    JsonElement jsonElement = jsonParser.parse(jsonString);
    Logs.d(jsonElement.isJsonArray() + "   " + jsonElement.isJsonObject());
    ArrayList arrayList = new ArrayList();
    if (jsonElement.isJsonObject()) {
        arrayList.add(gson.fromJson(jsonElement, HashMap.class));
    } else if (jsonElement.isJsonArray()) {
        arrayList = getListFromJson(jsonString, new TypeToken<ArrayList>() {
        });
    }
    return arrayList;
}
 
Example 14
Source File: GsonUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 判断字符串是否 JSON Array 格式
 * @param json 待校验 JSON String
 * @return {@code true} yes, {@code false} no
 */
public static boolean isJSONArray(final String json) {
    JsonElement jsonElement;
    try {
        jsonElement = new JsonParser().parse(json);
    } catch (Exception e) {
        return false;
    }
    if (jsonElement == null) return false;
    return jsonElement.isJsonArray();
}
 
Example 15
Source File: UpdateChecker.java    From ShopChest with MIT License 5 votes vote down vote up
/**
 * Check if an update is needed
 *
 * @return {@link UpdateCheckerResult#TRUE} if an update is available,
 *         {@link UpdateCheckerResult#FALSE} if no update is needed or
 *         {@link UpdateCheckerResult#ERROR} if an error occurred
 */
public UpdateCheckerResult check() {
    try {
        plugin.debug("Checking for updates...");

        URL url = new URL("https://api.spiget.org/v2/resources/11431/versions?size=1&page=1&sort=-releaseDate");
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("User-Agent", "ShopChest/UpdateChecker");

        InputStreamReader reader = new InputStreamReader(conn.getInputStream());
        JsonElement element = new JsonParser().parse(reader);

        if (element.isJsonArray()) {
            JsonObject result = element.getAsJsonArray().get(0).getAsJsonObject();
            String id = result.get("id").getAsString();
            version = result.get("name").getAsString();
            link = "https://www.spigotmc.org/resources/shopchest.11431/download?version=" + id;
        } else {
            plugin.debug("Failed to check for updates");
            plugin.debug("Result: " + element.toString());
            return UpdateCheckerResult.ERROR;
        }

        if (plugin.getDescription().getVersion().equals(version)) {
            plugin.debug("No update found");
            return UpdateCheckerResult.FALSE;
        } else {
            plugin.debug("Update found: " + version);
            return UpdateCheckerResult.TRUE;
        }

    } catch (Exception e) {
        plugin.debug("Failed to check for updates");
        plugin.debug(e);
        return UpdateCheckerResult.ERROR;
    }
}
 
Example 16
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 17
Source File: ModelLabelProvider.java    From olca-app with Mozilla Public License 2.0 5 votes vote down vote up
private String getValue(JsonElement element, JsonElement parent) {
	if (element == null)
		return "";
	if (element.isJsonArray() && element.getAsJsonArray().size() == 0)
		return "";
	if (element.isJsonNull())
		return "";
	if (!element.isJsonObject())
		return element.getAsString();
	return ModelUtil.getObjectLabel(parent, element.getAsJsonObject());
}
 
Example 18
Source File: VersionChecker.java    From EagleFactions with MIT License 5 votes vote down vote up
public static boolean isLatest(String version)
{
    String latest = "https://ore.spongepowered.org/api/v1/projects/eaglefactions/versions";
    String currentTag = "https://ore.spongepowered.org/api/v1/projects/eaglefactions/versions/" + version;

    String latestJsonData = sendRequest(latest);
    String currentJsonData = sendRequest(currentTag);

    if (latestJsonData != null && currentJsonData != null)
    {
        JsonParser parser = new JsonParser();
        JsonElement latestJsonElement = parser.parse(latestJsonData);
        JsonElement currentJsonElement = parser.parse(currentJsonData);

        if (latestJsonElement.isJsonArray())
        {
            JsonArray latestJsonArray = latestJsonElement.getAsJsonArray();
            JsonElement latestRelease = latestJsonArray.get(0);

            Date latestReleaseDate = Date.from(Instant.parse(latestRelease.getAsJsonObject().get("createdAt").getAsString()));
            Date currentReleaseDate = Date.from(Instant.parse(currentJsonElement.getAsJsonObject().get("createdAt").getAsString()));

            if (currentReleaseDate.before(latestReleaseDate)) return false;
        }
    }

    return true;
}
 
Example 19
Source File: MergeJsonBuilder.java    From java-slack-sdk with MIT License 5 votes vote down vote up
private static void mergeJsonObjects(
        JsonObject leftObj,
        JsonObject rightObj,
        ConflictStrategy conflictStrategy) throws JsonConflictException {

    for (Map.Entry<String, JsonElement> rightEntry : rightObj.entrySet()) {
        String rightKey = rightEntry.getKey();
        JsonElement rightVal = rightEntry.getValue();
        if (leftObj.has(rightKey)) {
            //conflict
            JsonElement leftVal = leftObj.get(rightKey);
            if (leftVal.isJsonArray() && rightVal.isJsonArray()) {
                JsonArray leftArr = leftVal.getAsJsonArray();
                JsonArray rightArr = rightVal.getAsJsonArray();
                for (int i = 0; i < rightArr.size(); i++) {
                    JsonElement rightArrayElem = rightArr.get(i);
                    if (!leftArr.contains(rightArrayElem)) {
                        // remove temporarily added an empty string
                        if (rightArrayElem.isJsonObject()
                                && leftArr.size() == 1
                                && leftArr.get(i).isJsonPrimitive()
                                && leftArr.get(i).getAsString().equals("")) {
                            leftArr.remove(0);
                        }
                        leftArr.add(rightArrayElem);
                    }
                }
            } else if (leftVal.isJsonObject() && rightVal.isJsonObject()) {
                //recursive merging
                mergeJsonObjects(leftVal.getAsJsonObject(), rightVal.getAsJsonObject(), conflictStrategy);
            } else {//not both arrays or objects, normal merge with conflict resolution
                handleMergeConflict(rightKey, leftObj, leftVal, rightVal, conflictStrategy);
            }
        } else {//no conflict, add to the object
            leftObj.add(rightKey, rightVal);
        }
    }
}
 
Example 20
Source File: VariantJsonDeserializer.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Variant deserialize ( final JsonElement json, final Type typeOfT, final JsonDeserializationContext context ) throws JsonParseException
{
    if ( json.isJsonNull () )
    {
        return null;
    }

    if ( json instanceof JsonPrimitive )
    {
        return decodeFromPrimitive ( json );
    }

    if ( json instanceof JsonObject )
    {
        final JsonObject jsonObj = (JsonObject)json;
        final JsonElement type = jsonObj.get ( VariantJson.FIELD_TYPE );
        final JsonElement value = jsonObj.get ( VariantJson.FIELD_VALUE );

        if ( type == null || type.isJsonNull () )
        {
            if ( value == null )
            {
                throw new JsonParseException ( String.format ( "Variant encoded as object must have a field '%s'", VariantJson.FIELD_VALUE ) );
            }
            return Variant.valueOf ( value.getAsString () );
        }

        if ( !type.isJsonPrimitive () )
        {
            throw new JsonParseException ( String.format ( "Variant field '%s' must be a string containing the variant type (%s)", VariantJson.FIELD_TYPE, StringHelper.join ( VariantType.values (), ", " ) ) );
        }

        final String typeStr = type.getAsString ();

        if ( typeStr.equals ( "NULL" ) )
        {
            return Variant.NULL;
        }

        if ( value == null || value.isJsonNull () )
        {
            throw new JsonParseException ( String.format ( "The type '%s' does not support a null value. Use variant type NULL instead.", typeStr ) );
        }

        if ( value.isJsonObject () || value.isJsonArray () )
        {
            throw new JsonParseException ( "The variant value must be a JSON primitive matching the type. Arrays and objects are not supported" );
        }

        switch ( type.getAsString () )
        {
            case "BOOLEAN":
                return Variant.valueOf ( value.getAsBoolean () );
            case "STRING":
                return Variant.valueOf ( value.getAsString () );
            case "DOUBLE":
                return Variant.valueOf ( value.getAsDouble () );
            case "INT32":
                return Variant.valueOf ( value.getAsInt () );
            case "INT64":
                return Variant.valueOf ( value.getAsLong () );
            default:
                throw new JsonParseException ( String.format ( "Type '%s' is unknown (known types: %s)", StringHelper.join ( VariantType.values (), ", " ) ) );
        }
    }

    throw new JsonParseException ( "Unknown serialization of Variant type" );
}