Example usage for com.google.gson JsonObject getAsJsonArray

List of usage examples for com.google.gson JsonObject getAsJsonArray

Introduction

In this page you can find the example usage for com.google.gson JsonObject getAsJsonArray.

Prototype

public JsonArray getAsJsonArray(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonArray.

Usage

From source file:joop.student.hu.nl.WeatherForecast.java

private String constructWeatherForecastFromJsonResponse(String response, int daysInTheFuture) {
    Gson gson = new GsonBuilder().create();
    JsonObject job = gson.fromJson(response, JsonObject.class);
    JsonObject j = gson.fromJson(//from   w  w w .j  a  v a  2 s. com
            job.getAsJsonArray("list").get(offsetToFindAfternoonForecast + forecastsPerDay * daysInTheFuture)
                    .getAsJsonObject().toString(),
            JsonObject.class);
    String temperature = j.getAsJsonObject("main").get("temp").toString();
    String humidity = j.getAsJsonObject("main").get("humidity").toString();
    String overallForecast = j.getAsJsonArray("weather").get(0).getAsJsonObject().get("description").toString()
            .replaceAll("\"", "");
    return overallForecast + ". With an average temperature of " + temperature + " degrees Celsius and a "
            + "humidity level of " + humidity + " percent";
}

From source file:jsonchannelparse.country.java

public void load(JsonObject countryJson) {

    c5all.clear();//from  w w  w .jav a 2s  .  c om
    c5dfs.clear();
    c5cln.clear();

    name = countryJson.get("name").toString();
    key = countryJson.get("key").toString();
    code = countryJson.get("code").getAsInt();
    JsonArray channels = countryJson.getAsJsonArray("channels_na");

    for (JsonElement ch : channels) {
        c5all.add(Integer.parseInt(ch.getAsString()));
    }

    channels = countryJson.getAsJsonArray("channels_na_dfs");

    for (JsonElement ch : channels) {
        c5dfs.add(Integer.parseInt(ch.getAsString()));
    }
    c5cln.addAll(c5all);
    c5cln.removeAll(c5dfs);
}

From source file:logic.Util.java

public static List<CVE> getCvesDetails(List<CVE> cves, ProgressUpdateListener progressListener) {
    List<CVE> completedCves = veryfyCves(cves);
    int progress = 0;
    System.out.println("CVES size: " + cves.size());
    for (CVE cve : cves) {
        if (!completedCves.contains(cve))
            try {
                JsonObject cveDetails = getData(URL_API_CVE + cve.getId()).getAsJsonObject();
                JsonObject impact = cveDetails.getAsJsonObject("impact");
                JsonObject access = cveDetails.getAsJsonObject("access");

                CVE newCve = getCveFromJson(cve, access, cveDetails.get("cvss"), cveDetails.get("cwe"), impact);

                JsonArray capec = cveDetails.getAsJsonArray("capec");
                newCve.setAttackWays(getCapecFromJSon(capec));
                completedCves.add(newCve);

                progress++;/*ww w .  ja v a  2 s. com*/
                if (progressListener.onProgressUpdate(progress))
                    return null;
            } catch (Exception e) {
                e.printStackTrace();
            }
    }

    return completedCves;
}

From source file:login.SelectIP.java

private void setUpBaseData() throws IOException {
    final UpdateInterface update1 = lb.getRetrofit().create(UpdateInterface.class);
    final RefralAPI refralAPI = lb.getRetrofit().create(RefralAPI.class);
    final JsonObject branchMaster = update1.GetBranchMaster().execute().body();
    final JsonObject refmaster = refralAPI.GetSalesmanMaster().execute().body();
    final JsonArray branchArray = branchMaster.getAsJsonArray("data");
    final JsonArray refMaster = refmaster.getAsJsonArray("data");
    final JsonArray yearArray = branchMaster.getAsJsonArray("year");
    if (branchArray.size() > 0) {
        for (int i = 0; i < branchArray.size(); i++) {
            BranchMasterModel model = new Gson().fromJson(branchArray.get(i).getAsJsonObject().toString(),
                    BranchMasterModel.class);
            Constants.BRANCH.add(model);
        }/*w  w  w  .ja v  a 2 s .  com*/
    }
    if (yearArray.size() > 0) {
        for (int i = 0; i < yearArray.size(); i++) {
            DBYearModel model = new Gson().fromJson(yearArray.get(i).getAsJsonObject().toString(),
                    DBYearModel.class);
            Constants.DBYMS.add(model);
        }
    }
    if (refMaster.size() > 0) {
        for (int i = 0; i < refMaster.size(); i++) {
            RefModel model = new Gson().fromJson(refMaster.get(i).getAsJsonObject().toString(), RefModel.class);
            Constants.REFERAL.add(model);
        }
    }
    getTaxMaster();
}

From source file:login.SelectIP.java

private void getTaxMaster() {
    Call<JsonObject> call = lb.getRetrofit().create(StartUpAPI.class).getDataFromServer("7");
    try {//  www .j  av a2  s .c o  m
        JsonObject data = call.execute().body();
        System.out.println(data.toString());
        int status = data.get("result").getAsInt();
        if (status == 1) {
            Constants.TAX.clear();
            JsonArray array = data.getAsJsonArray("data");
            for (int i = 0; i < array.size(); i++) {
                TaxMasterModel taxMasterModel = new Gson().fromJson(array.get(i), TaxMasterModel.class);
                Constants.TAX.add(taxMasterModel);
            }
        } else {
        }
    } catch (Exception ex) {
        lb.showMessageDailog(ex.getMessage());
    }
}

From source file:lolxmpp.api.data.Mastery.java

License:Open Source License

/**
 * @deprecated Only for API initialization.
 * @param api RiotAPI Key// ww  w.  ja  va 2  s.  c om
 */
public static void loadMasteryIcons(RiotAPI rapi) {
    try {
        JsonObject jobject = rapi.makeRequest("/lol/static-data/v3/masteries?tags=all");
        if (jobject.has("version")) {
            String currentVersion = jobject.get("version").getAsString();
            String spriteUrl = "http://ddragon.leagueoflegends.com/cdn/" + currentVersion
                    + "/img/sprite/mastery0.png";
            BufferedImage image = ImageIO.read(new URL(spriteUrl));

            JsonObject data = jobject.get("data").getAsJsonObject();
            for (Entry<String, JsonElement> member : data.entrySet()) {
                JsonObject dataObj = data.get(member.getKey()).getAsJsonObject();

                long id = dataObj.get("id").getAsLong();

                String name = dataObj.get("name").getAsString();
                names.put(id, name);

                String masteryTreeStr = dataObj.get("masteryTree").getAsString();
                masteryTree.put(id, masteryTreeStr);

                int rank = dataObj.get("ranks").getAsInt();
                ranks.put(id, rank);

                String[] descriptionsr = new String[rank];

                Iterator<JsonElement> it = dataObj.getAsJsonArray("description").iterator();

                int i = 0;
                while (it.hasNext()) {
                    descriptionsr[i] = it.next().getAsString();
                    i++;
                }

                descriptions.put(id, descriptionsr);

                JsonObject imageObject = dataObj.get("image").getAsJsonObject();
                int w = imageObject.get("w").getAsInt();
                int h = imageObject.get("h").getAsInt();
                int x = imageObject.get("x").getAsInt();
                int y = imageObject.get("y").getAsInt();

                images.put(id, image.getSubimage(x, y, w, h));
            }
        }
    } catch (APIException e) {
        e.printStackTrace();
    } catch (JsonSyntaxException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:magrathea.marvin.desktop.host.dao.HTTPRequestHostDAO.java

/**
 * Processa el JSON i retorna un array JSON per construr els objectes
 *
 * @param in Reader que retorna la connexi
 * @param node Nom del objectes JSON o null si es un array
 * @return un array d'objectes Json.//w  ww  .  ja va2 s.  c o m
 */
private JsonArray getArrayFromJson(Reader in, String node) {
    JsonArray jarray = null;

    JsonElement jelement = new JsonParser().parse(in);
    if (node != null) {
        JsonObject jobject = jelement.getAsJsonObject();
        jarray = jobject.getAsJsonArray(node);
    } else {
        jarray = jelement.getAsJsonArray();
    }
    return jarray;
}

From source file:matteroverdrive.client.resources.data.WeaponMetadataSectionSerializer.java

License:Open Source License

@Override
public WeaponMetadataSection deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jsonobject = JsonUtils.getJsonElementAsJsonObject(json, "metadata section");
    Vec3 scopePosition = null;/*from   w w w .  jav  a2 s.  c o  m*/
    try {
        JsonArray array = jsonobject.getAsJsonArray("scope_position");
        if (array.size() >= 3) {
            scopePosition = Vec3.createVectorHelper(array.get(0).getAsDouble(), array.get(1).getAsDouble(),
                    array.get(2).getAsDouble());
        }
    } catch (ClassCastException classcastexception) {
        throw new JsonParseException(
                "Invalid weapon->scope_position: expected array, was " + jsonobject.get("scope_position"),
                classcastexception);
    }
    return new WeaponMetadataSection(scopePosition);
}

From source file:me.gnat008.perworldinventory.data.serializers.DeprecatedMethodUtil.java

License:Open Source License

/**
 * A method to deserialize a BannerMeta object from a JSONObject. This method assumes that the JSONArrays containing
 * the colors and pattern types are the same length.
 *
 * @param json The JSONObject of the BannerMeta to deserialize
 * @return The BannerMeta/*from ww w  .j ava2s.  c om*/
 */
public static BannerMeta getBannerMeta(JsonObject json) {
    BannerMeta dummy = (BannerMeta) new ItemStack(Material.BANNER).getItemMeta();
    if (json.has("base-color"))
        dummy.setBaseColor(DyeColor.getByDyeData(Byte.parseByte("" + json.get("base-color"))));

    JsonArray colors = json.getAsJsonArray("colors");
    JsonArray patternTypes = json.getAsJsonArray("pattern-types");
    for (int i = 0; i < colors.size() - 1; i++) {
        dummy.addPattern(
                new Pattern(DyeColor.getByDyeData(Integer.valueOf(colors.get(i).getAsInt()).byteValue()),
                        PatternType.getByIdentifier(patternTypes.get(i).getAsString())));
    }

    return dummy;
}

From source file:me.gnat008.perworldinventory.data.serializers.DeprecatedMethodUtil.java

License:Open Source License

/**
 * Get BookMeta from a JSONObject./* www  .jav a 2  s .  c om*/
 *
 * @param json The JsonObject of the BannerMeta to deserialize
 * @return The BookMeta constructed
 */
public static BookMeta getBookMeta(JsonObject json) {
    ItemStack dummyItems = new ItemStack(Material.WRITTEN_BOOK, 1);
    BookMeta meta = (BookMeta) dummyItems.getItemMeta();
    String title = null, author = null;
    JsonArray pages = null;
    if (json.has("title"))
        title = json.get("title").getAsString();
    if (json.has("author"))
        author = json.get("author").getAsString();
    if (json.has("pages"))
        pages = json.getAsJsonArray("pages");
    if (title != null)
        meta.setTitle(title);
    if (author != null)
        meta.setAuthor(author);
    if (pages != null) {
        String[] allPages = new String[pages.size()];
        for (int i = 0; i < pages.size() - 1; i++) {
            String page = pages.get(i).getAsString();
            if (page.isEmpty() || page == null)
                page = "";
            allPages[i] = page;
        }
        meta.setPages(allPages);
    }
    return meta;
}