Java Code Examples for com.google.gson.JsonArray.size()

The following are Jave code examples for showing how to use size() of the com.google.gson.JsonArray class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: CustomWorldGen   File: ForgeBlockStateV1.java   View Source Code Vote up 8 votes
public static float[] parseFloatArray(JsonElement e, int length, String prefix)
{
    if (!e.isJsonArray()) throw new JsonParseException(prefix + ": expected an array, got: " + e);
    JsonArray t = e.getAsJsonArray();
    if (t.size() != length) throw new JsonParseException(prefix + ": expected an array of length " + length + ", got: " + t.size());
    float[] ret = new float[length];
    for (int i = 0; i < length; i++)
    {
        try
        {
            ret[i] = t.get(i).getAsNumber().floatValue();
        }
        catch (ClassCastException ex)
        {
            throw new JsonParseException(prefix + " element: expected number, got: " + t.get(i));
        }
    }
    return ret;
}
 
Example 2
Project: BaseClient   File: BlockPart.java   View Source Code Vote up 6 votes
private Vector3f parsePosition(JsonObject p_178251_1_, String p_178251_2_)
{
    JsonArray jsonarray = JsonUtils.getJsonArray(p_178251_1_, p_178251_2_);

    if (jsonarray.size() != 3)
    {
        throw new JsonParseException("Expected 3 " + p_178251_2_ + " values, found: " + jsonarray.size());
    }
    else
    {
        float[] afloat = new float[3];

        for (int i = 0; i < afloat.length; ++i)
        {
            afloat[i] = JsonUtils.getFloat(jsonarray.get(i), p_178251_2_ + "[" + i + "]");
        }

        return new Vector3f(afloat[0], afloat[1], afloat[2]);
    }
}
 
Example 3
Project: Hub   File: GraouManager.java   View Source Code Vote up 6 votes
@Override
public void loadConfiguration(JsonArray rootJson)
{
    if (rootJson.size() == 0)
        return;

    for (int i = 0; i < rootJson.size(); i++)
    {
        JsonObject graouJson = rootJson.get(i).getAsJsonObject();

        Location catLocation = LocationUtils.str2loc(graouJson.get("cat").getAsString());
        Location doorLocation = LocationUtils.str2loc(graouJson.get("door").getAsString());
        Location treasureLocation = LocationUtils.str2loc(graouJson.get("treasure").getAsString());
        Location openingLocation = LocationUtils.str2loc(graouJson.get("opening").getAsString());

        Graou graou = new Graou(this.hub, catLocation, doorLocation, treasureLocation, openingLocation);

        this.interactions.add(graou);
        this.log(Level.INFO, "Registered Graou at '" + graouJson.get("cat").getAsString());
    }
}
 
Example 4
Project: CustomWorldGen   File: ServerStatusResponse.java   View Source Code Vote up 6 votes
public ServerStatusResponse.Players deserialize(JsonElement p_deserialize_1_, Type p_deserialize_2_, JsonDeserializationContext p_deserialize_3_) throws JsonParseException
{
    JsonObject jsonobject = JsonUtils.getJsonObject(p_deserialize_1_, "players");
    ServerStatusResponse.Players serverstatusresponse$players = new ServerStatusResponse.Players(JsonUtils.getInt(jsonobject, "max"), JsonUtils.getInt(jsonobject, "online"));

    if (JsonUtils.isJsonArray(jsonobject, "sample"))
    {
        JsonArray jsonarray = JsonUtils.getJsonArray(jsonobject, "sample");

        if (jsonarray.size() > 0)
        {
            GameProfile[] agameprofile = new GameProfile[jsonarray.size()];

            for (int i = 0; i < agameprofile.length; ++i)
            {
                JsonObject jsonobject1 = JsonUtils.getJsonObject(jsonarray.get(i), "player[" + i + "]");
                String s = JsonUtils.getString(jsonobject1, "id");
                agameprofile[i] = new GameProfile(UUID.fromString(s), JsonUtils.getString(jsonobject1, "name"));
            }

            serverstatusresponse$players.setPlayers(agameprofile);
        }
    }

    return serverstatusresponse$players;
}
 
Example 5
Project: CustomWorldGen   File: BlockPart.java   View Source Code Vote up 6 votes
private Vector3f parsePosition(JsonObject object, String memberName)
{
    JsonArray jsonarray = JsonUtils.getJsonArray(object, memberName);

    if (jsonarray.size() != 3)
    {
        throw new JsonParseException("Expected 3 " + memberName + " values, found: " + jsonarray.size());
    }
    else
    {
        float[] afloat = new float[3];

        for (int i = 0; i < afloat.length; ++i)
        {
            afloat[i] = JsonUtils.getFloat(jsonarray.get(i), memberName + "[" + i + "]");
        }

        return new Vector3f(afloat[0], afloat[1], afloat[2]);
    }
}
 
Example 6
Project: jSpace   File: TemplateDeserializer.java   View Source Code Vote up 6 votes
@Override
public Template deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
		throws JsonParseException {
	if (!json.isJsonArray()) {
		throw new JsonParseException("Unexpected JsonElement!");
	}
	JsonArray jsa = (JsonArray) json;
	jSonUtils utils = jSonUtils.getInstance();
	TemplateField[] data = new TemplateField[jsa.size()];
	for (int i = 0; i < jsa.size(); i++) {
		try {
			data[i] = utils.templateFromJSon(jsa.get(i), context);
		} catch (ClassCastException e) {
			throw new JsonParseException(e);
		}
	}
	return new Template(data);
}
 
Example 7
Project: SamaGamesCore   File: NameFetcher.java   View Source Code Vote up 6 votes
public static List<String> nameHistoryFromUuid(UUID uuid)
{
    URLConnection connection;
    try
    {
        connection = new URL("https://api.mojang.com/user/profiles/"
                + uuid.toString().replace("-", "").toLowerCase() + "/names"
        ).openConnection();
        String text = new Scanner(connection.getInputStream(), "UTF-8").useDelimiter("\\Z").next();
        JsonArray list = (JsonArray) parser.parse(text);
        List<String> names = new ArrayList<>();
        for (int i = 0; i < list.size(); i++)
            names.add(((JsonObject) list.get(i)).get("name").getAsString());
        return names;
    } catch (IOException e)
    {
        e.printStackTrace();
    }
    return null;
}
 
Example 8
Project: ultimate-geojson   File: MultiLineStringDeserializer.java   View Source Code Vote up 6 votes
@Override
public MultiLineStringDto deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {

	MultiLineStringDto dto = new MultiLineStringDto();
	List<LineStringDto> lines = new ArrayList<>();
	dto.setLines(lines);

	JsonObject asJsonObject = json.getAsJsonObject();
	JsonArray jsonArray = asJsonObject.get("coordinates").getAsJsonArray();
	Type positionCollectionType = new TypeToken<List<PositionDto>>() {
	}.getType();
	for (int i = 0; i < jsonArray.size(); i++) {
		List<PositionDto> positions = context.deserialize(jsonArray.get(i), positionCollectionType);
		LineStringDto line = new LineStringDto();
		line.setPositions(positions);
		lines.add(line);
	}

	dto.setBbox(BoundingBoxParser.parseBbox(asJsonObject, context));
	
	return dto;
}
 
Example 9
Project: ViperBot   File: RecognitionResult.java   View Source Code Vote up 6 votes
/** Returns true if the result JSON is for video. */
private static boolean isVideoResult(JsonObject result) {
  if (result.get("tag") != null && result.get("tag").isJsonObject()) {
    JsonElement timestamps = result.get("tag").getAsJsonObject().get("timestamps");
    if (timestamps != null && timestamps.isJsonArray()) {
      return true;
    }
  }
  if (result.get("embed") != null && result.get("embed").isJsonArray()) {
    JsonArray embedArray = result.get("embed").getAsJsonArray();
    if (embedArray.size() > 0 && embedArray.get(0).isJsonArray()) {
      return true;
    }
  }
  return false;
}
 
Example 10
Project: Phoenix-for-VK   File: AbsAdapter.java   View Source Code Vote up 5 votes
protected static int[] parseIntArray(JsonArray array){
    int[] list = new int[array.size()];
    for(int i = 0; i < array.size(); i++){
        list[i] = array.get(i).getAsInt();
    }

    return list;
}
 
Example 11
Project: Habitizer   File: LoginActivity.java   View Source Code Vote up 5 votes
/**
 * Checks if network is available and gets habits accordingly
 * @param username
 */
private void postLogin(String username) {
    Type listType;
    if(Utilities.isNetworkAvailable(LoginActivity.this)){
        ElasticsearchController.GetItemsTask getHabitsArrayGetTask = new ElasticsearchController.GetItemsTask();
        getHabitsArrayGetTask.execute(DummyMainActivity.Habit_Index, "username", username);
        try{
            JsonArray jsonHabits =  getHabitsArrayGetTask.get();
            DummyMainActivity.myHabits = new ArrayList<>();
            for (int i = 0; i < jsonHabits.size(); i++){
                Habit h = new Habit();
                JsonObject job  = jsonHabits.get(i).getAsJsonObject();
                h.fromJsonObject(job);
                DummyMainActivity.myHabits.add(h);
            }
        }catch (Exception e){
            Log.d("ESC", "Adding habits in login.");
        }
    }else{

        listType = new TypeToken<ArrayList<Habit>>(){}.getType();
        DummyMainActivity.myHabits =  FileController.loadFromFile(LoginActivity.this, DummyMainActivity.HABITFILENAME, listType);
        if ( DummyMainActivity.myHabits == null){
            DummyMainActivity.myHabits = new ArrayList<>();
        }
    }
}
 
Example 12
Project: CustomWorldGen   File: ItemTransformVec3f.java   View Source Code Vote up 5 votes
private Vector3f parseVector3f(JsonObject jsonObject, String key, Vector3f defaultValue)
{
    if (!jsonObject.has(key))
    {
        return defaultValue;
    }
    else
    {
        JsonArray jsonarray = JsonUtils.getJsonArray(jsonObject, key);

        if (jsonarray.size() != 3)
        {
            throw new JsonParseException("Expected 3 " + key + " values, found: " + jsonarray.size());
        }
        else
        {
            float[] afloat = new float[3];

            for (int i = 0; i < afloat.length; ++i)
            {
                afloat[i] = JsonUtils.getFloat(jsonarray.get(i), key + "[" + i + "]");
            }

            return new Vector3f(afloat[0], afloat[1], afloat[2]);
        }
    }
}
 
Example 13
Project: Hydrograph   File: LingualSchemaCreatorTest.java   View Source Code Vote up 5 votes
private String getConvertedArrayToString(JsonArray array) {
	String string = "";
	for (int i = 0; i < array.size(); i++)
		string += (i == array.size() - 1) ? array.get(i).getAsString() : array.get(i).getAsString() + ", ";

	return string;
}
 
Example 14
Project: PACE   File: LocalEncryptionKeyContainer.java   View Source Code Vote up 5 votes
/**
 * Read the encryption key container from the reader.
 *
 * @param in
 *          Input reader.
 * @return Parsed encryption key container.
 */
public static LocalEncryptionKeyContainer read(Reader in) {
  LocalEncryptionKeyContainer container = new LocalEncryptionKeyContainer();
  JsonParser parser = new JsonParser();

  JsonObject data = parser.parse(in).getAsJsonObject();
  int version = data.getAsJsonPrimitive("version").getAsInt();

  switch (version) {
    case 1:
      JsonArray keys = data.getAsJsonArray("keys");
      for (int i = 0; i < keys.size(); i++) {
        JsonObject key = keys.get(i).getAsJsonObject();
        if (key.has("attribute")) {
          container.addKey(key.getAsJsonPrimitive("attribute").getAsString(), key.getAsJsonPrimitive("id").getAsString(), key.getAsJsonPrimitive("version")
              .getAsInt(), Base64.getDecoder().decode(key.getAsJsonPrimitive("key").getAsString()), false);
        } else {
          container.addKey(null, key.getAsJsonPrimitive("id").getAsString(), key.getAsJsonPrimitive("version").getAsInt(),
              Base64.getDecoder().decode(key.getAsJsonPrimitive("key").getAsString()), false);
        }
      }
      break;

    default:
      throw new UnsupportedOperationException("unsupported file version");
  }

  return container;
}
 
Example 15
Project: Phoenix-for-VK   File: PhotoAlbumDtoAdapter.java   View Source Code Vote up 5 votes
@Override
public VKApiPhotoAlbum deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    JsonObject root = json.getAsJsonObject();

    VKApiPhotoAlbum album = new VKApiPhotoAlbum();

    album.id = optInt(root, "id");
    album.thumb_id = optInt(root, "thumb_id");
    album.owner_id = optInt(root, "owner_id");
    album.title = optString(root, "title");
    album.description = optString(root, "description");
    album.created = optLong(root, "created");
    album.updated = optLong(root, "updated");
    album.size = optInt(root, "size");
    album.can_upload = optInt(root, "can_upload") == 1;
    album.thumb_src = optString(root, "thumb_src");

    if(root.has("privacy_view")){
        album.privacy_view = context.deserialize(root.getAsJsonArray("privacy_view"), VkApiPrivacy.class);
    }

    if(root.has("privacy_comment")){
        album.privacy_comment = context.deserialize(root.getAsJsonArray("privacy_comment"), VkApiPrivacy.class);
    }

    if(root.has("sizes")){
        JsonArray sizesArray = root.getAsJsonArray("sizes");
        album.photo = new ArrayList<>(sizesArray.size());

        for(int i = 0; i < sizesArray.size(); i++){
            album.photo.add(context.deserialize(sizesArray.get(i).getAsJsonObject(), PhotoSizeDto.class));
        }
    } else {
        album.photo = new ArrayList<>(3);
        album.photo.add(PhotoSizeDto.create(PhotoSizeDto.Type.S, "http://vk.com/images/s_noalbum.png"));
        album.photo.add(PhotoSizeDto.create(PhotoSizeDto.Type.M, "http://vk.com/images/m_noalbum.png"));
        album.photo.add(PhotoSizeDto.create(PhotoSizeDto.Type.X, "http://vk.com/images/x_noalbum.png"));
    }

    album.upload_by_admins_only = optInt(root, "upload_by_admins_only") == 1;
    album.comments_disabled = optInt(root, "comments_disabled") == 1;
    return album;
}
 
Example 16
Project: EasyReader   File: NewsJsonUtils.java   View Source Code Vote up 5 votes
/**
 * 将获取到的json转换为新闻列表对象
 * @param res
 * @param value
 * @return
 */
public static List<NewsListBean.NewsBean> readJsonNewsBeans(String res, String value) {
    List<NewsListBean.NewsBean> beans = new ArrayList<NewsListBean.NewsBean>();
    try {
        JsonParser parser = new JsonParser();
        JsonObject jsonObj = parser.parse(res).getAsJsonObject();
        JsonElement jsonElement = jsonObj.get(value);
        if(jsonElement == null) {
            return null;
        }
        JsonArray jsonArray = jsonElement.getAsJsonArray();
        for (int i = 1; i < jsonArray.size(); i++) {
            JsonObject jo = jsonArray.get(i).getAsJsonObject();
            if (jo.has("skipType") && "special".equals(jo.get("skipType").getAsString())) {
                continue;
            }
            if (jo.has("TAGS") && !jo.has("TAG")) {
                continue;
            }

            if (!jo.has("imgextra")) {
                NewsListBean.NewsBean news = JsonUtils.deserialize(jo, NewsListBean.NewsBean.class);
                beans.add(news);
            }
        }
    } catch (Exception e) {
    }
    return beans;
}
 
Example 17
Project: BaseClient   File: PlayerItemParser.java   View Source Code Vote up 4 votes
public static PlayerItemModel parseItemModel(JsonObject p_parseItemModel_0_)
{
    String s = Json.getString(p_parseItemModel_0_, "type");

    if (!Config.equals(s, "PlayerItem"))
    {
        throw new JsonParseException("Unknown model type: " + s);
    }
    else
    {
        int[] aint = Json.parseIntArray(p_parseItemModel_0_.get("textureSize"), 2);
        checkNull(aint, "Missing texture size");
        Dimension dimension = new Dimension(aint[0], aint[1]);
        boolean flag = Json.getBoolean(p_parseItemModel_0_, "usePlayerTexture", false);
        JsonArray jsonarray = (JsonArray)p_parseItemModel_0_.get("models");
        checkNull(jsonarray, "Missing elements");
        Map map = new HashMap();
        List list = new ArrayList();
        new ArrayList();

        for (int i = 0; i < jsonarray.size(); ++i)
        {
            JsonObject jsonobject = (JsonObject)jsonarray.get(i);
            String s1 = Json.getString(jsonobject, "baseId");

            if (s1 != null)
            {
                JsonObject jsonobject1 = (JsonObject)map.get(s1);

                if (jsonobject1 == null)
                {
                    Config.warn("BaseID not found: " + s1);
                    continue;
                }

                for (Entry<String, JsonElement> entry : jsonobject1.entrySet())
                {
                    if (!jsonobject.has((String)entry.getKey()))
                    {
                        jsonobject.add((String)entry.getKey(), (JsonElement)entry.getValue());
                    }
                }
            }

            String s2 = Json.getString(jsonobject, "id");

            if (s2 != null)
            {
                if (!map.containsKey(s2))
                {
                    map.put(s2, jsonobject);
                }
                else
                {
                    Config.warn("Duplicate model ID: " + s2);
                }
            }

            PlayerItemRenderer playeritemrenderer = parseItemRenderer(jsonobject, dimension);

            if (playeritemrenderer != null)
            {
                list.add(playeritemrenderer);
            }
        }

        PlayerItemRenderer[] aplayeritemrenderer = (PlayerItemRenderer[])((PlayerItemRenderer[])list.toArray(new PlayerItemRenderer[list.size()]));
        return new PlayerItemModel(dimension, flag, aplayeritemrenderer);
    }
}
 
Example 18
Project: ibm-cloud-devops   File: AbstractDevOpsAction.java   View Source Code Vote up 4 votes
public static String getSpaceId(String token, String spaceName, String environment, Boolean debug_mode) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    String spaces_url = chooseSpacesUrl(environment);
    if(debug_mode){
        LOGGER.info("GET SPACE_GUID URL:" + spaces_url + spaceName);
    }

    try {
        HttpGet httpGet = new HttpGet(spaces_url + URLEncoder.encode(spaceName, "UTF-8").replaceAll("\\+", "%20"));

        httpGet = addProxyInformation(httpGet);

        httpGet.setHeader("Authorization", token);
        CloseableHttpResponse response = null;

        response = httpClient.execute(httpGet);
        String resStr = EntityUtils.toString(response.getEntity());

        if(debug_mode){
            LOGGER.info("RESPONSE FROM SPACES API:" + response.getStatusLine().toString());
        }
        if (response.getStatusLine().toString().contains("200")) {
            // get 200 response
            JsonParser parser = new JsonParser();
            JsonElement element = parser.parse(resStr);
            JsonObject obj = element.getAsJsonObject();
            JsonArray resources = obj.getAsJsonArray("resources");

            if(resources.size() > 0) {
                JsonObject resource = resources.get(0).getAsJsonObject();
                JsonObject metadata = resource.getAsJsonObject("metadata");
                if(debug_mode){
                    LOGGER.info("SPACE_ID:" + String.valueOf(metadata.get("guid")).replaceAll("\"", ""));
                }
                return String.valueOf(metadata.get("guid")).replaceAll("\"", "");
            }
            else {
                if(debug_mode){
                    LOGGER.info("RETURNED NO SPACES.");
                }
                return null;
            }

        } else {
            if(debug_mode){
                LOGGER.info("RETURNED STATUS CODE OTHER THAN 200. RESPONSE: " + response.getStatusLine().toString());
            }
            return null;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 19
Project: Backmemed   File: SetAttributes.java   View Source Code Vote up 4 votes
public static SetAttributes.Modifier deserialize(JsonObject jsonObj, JsonDeserializationContext context)
{
    String s = JsonUtils.getString(jsonObj, "name");
    String s1 = JsonUtils.getString(jsonObj, "attribute");
    int i = getOperationFromInt(JsonUtils.getString(jsonObj, "operation"));
    RandomValueRange randomvaluerange = (RandomValueRange)JsonUtils.deserializeClass(jsonObj, "amount", context, RandomValueRange.class);
    UUID uuid = null;
    EntityEquipmentSlot[] aentityequipmentslot;

    if (JsonUtils.isString(jsonObj, "slot"))
    {
        aentityequipmentslot = new EntityEquipmentSlot[] {EntityEquipmentSlot.fromString(JsonUtils.getString(jsonObj, "slot"))};
    }
    else
    {
        if (!JsonUtils.isJsonArray(jsonObj, "slot"))
        {
            throw new JsonSyntaxException("Invalid or missing attribute modifier slot; must be either string or array of strings.");
        }

        JsonArray jsonarray = JsonUtils.getJsonArray(jsonObj, "slot");
        aentityequipmentslot = new EntityEquipmentSlot[jsonarray.size()];
        int j = 0;

        for (JsonElement jsonelement : jsonarray)
        {
            aentityequipmentslot[j++] = EntityEquipmentSlot.fromString(JsonUtils.getString(jsonelement, "slot"));
        }

        if (aentityequipmentslot.length == 0)
        {
            throw new JsonSyntaxException("Invalid attribute modifier slot; must contain at least one entry.");
        }
    }

    if (jsonObj.has("id"))
    {
        String s2 = JsonUtils.getString(jsonObj, "id");

        try
        {
            uuid = UUID.fromString(s2);
        }
        catch (IllegalArgumentException var12)
        {
            throw new JsonSyntaxException("Invalid attribute modifier id \'" + s2 + "\' (must be UUID format, with dashes)");
        }
    }

    return new SetAttributes.Modifier(s, s1, i, randomvaluerange, aentityequipmentslot, uuid);
}
 
Example 20
Project: BaseClient   File: PlayerConfigurationParser.java   View Source Code Vote up 4 votes
public PlayerConfiguration parsePlayerConfiguration(JsonElement p_parsePlayerConfiguration_1_)
{
    if (p_parsePlayerConfiguration_1_ == null)
    {
        throw new JsonParseException("JSON object is null, player: " + this.player);
    }
    else
    {
        JsonObject jsonobject = (JsonObject)p_parsePlayerConfiguration_1_;
        PlayerConfiguration playerconfiguration = new PlayerConfiguration();
        JsonArray jsonarray = (JsonArray)jsonobject.get("items");

        if (jsonarray != null)
        {
            for (int i = 0; i < jsonarray.size(); ++i)
            {
                JsonObject jsonobject1 = (JsonObject)jsonarray.get(i);
                boolean flag = Json.getBoolean(jsonobject1, "active", true);

                if (flag)
                {
                    String s = Json.getString(jsonobject1, "type");

                    if (s == null)
                    {
                        Config.warn("Item type is null, player: " + this.player);
                    }
                    else
                    {
                        String s1 = Json.getString(jsonobject1, "model");

                        if (s1 == null)
                        {
                            s1 = "items/" + s + "/model.cfg";
                        }

                        PlayerItemModel playeritemmodel = this.downloadModel(s1);

                        if (playeritemmodel != null)
                        {
                            if (!playeritemmodel.isUsePlayerTexture())
                            {
                                String s2 = Json.getString(jsonobject1, "texture");

                                if (s2 == null)
                                {
                                    s2 = "items/" + s + "/users/" + this.player + ".png";
                                }

                                BufferedImage bufferedimage = this.downloadTextureImage(s2);

                                if (bufferedimage == null)
                                {
                                    continue;
                                }

                                playeritemmodel.setTextureImage(bufferedimage);
                                ResourceLocation resourcelocation = new ResourceLocation("optifine.net", s2);
                                playeritemmodel.setTextureLocation(resourcelocation);
                            }

                            playerconfiguration.addPlayerItemModel(playeritemmodel);
                        }
                    }
                }
            }
        }

        return playerconfiguration;
    }
}