Example usage for com.google.gson JsonArray get

List of usage examples for com.google.gson JsonArray get

Introduction

In this page you can find the example usage for com.google.gson JsonArray get.

Prototype

public JsonElement get(int i) 

Source Link

Document

Returns the ith element of the array.

Usage

From source file:com.fooock.shodan.model.banner.BannerDeserializer.java

License:Open Source License

@Override
public List<Banner> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    final List<Banner> banners = new ArrayList<>();
    if (json.isJsonNull()) {
        return banners;
    }//from   w w  w .  j a v  a2  s  .c o m
    JsonArray jsonArray = json.getAsJsonArray();
    if (jsonArray.isJsonNull()) {
        return banners;
    }
    for (JsonElement element : jsonArray) {
        JsonObject jsonObject = element.getAsJsonObject();
        JsonElement port = jsonObject.get("port");
        JsonElement ip = jsonObject.get("ip");
        JsonElement asn = jsonObject.get("asn");
        JsonElement data = jsonObject.get("data");
        JsonElement ipStr = jsonObject.get("ip_str");
        JsonElement ipv6 = jsonObject.get("ipv6");
        JsonElement timestamp = jsonObject.get("timestamp");
        JsonElement hostnames = jsonObject.get("hostnames");
        JsonElement domains = jsonObject.get("domains");
        JsonElement location = jsonObject.get("location");
        JsonElement options = jsonObject.get("opts");
        JsonElement metadata = jsonObject.get("_shodan");
        JsonElement ssl = jsonObject.get("ssl");

        JsonElement uptime = jsonObject.get("uptime");
        JsonElement link = jsonObject.get("link");
        JsonElement title = jsonObject.get("title");
        JsonElement html = jsonObject.get("html");
        JsonElement product = jsonObject.get("product");
        JsonElement version = jsonObject.get("version");
        JsonElement isp = jsonObject.get("isp");
        JsonElement os = jsonObject.get("os");
        JsonElement transport = jsonObject.get("transport");
        JsonElement devicetype = jsonObject.get("devicetype");
        JsonElement info = jsonObject.get("info");
        JsonElement cpe = jsonObject.get("cpe");

        final Banner banner = new Banner();
        if (port == null || port.isJsonNull()) {
            banner.setPort(0);
        } else {
            banner.setPort(port.getAsInt());
        }

        if (ip == null || ip.isJsonNull()) {
            banner.setIp(0);
        } else {
            banner.setIp(ip.getAsLong());
        }

        if (asn == null || asn.isJsonNull()) {
            banner.setAsn("unknown");
        } else {
            banner.setAsn(asn.getAsString());
        }

        if (data == null || data.isJsonNull()) {
            banner.setData("unknown");
        } else {
            banner.setData(data.getAsString());
        }

        if (ipStr == null || ipStr.isJsonNull()) {
            banner.setIpStr("unknown");
        } else {
            banner.setIpStr(ipStr.getAsString());
        }

        if (ipv6 == null || ipv6.isJsonNull()) {
            banner.setIpv6("unknown");
        } else {
            banner.setIpv6(ipv6.getAsString());
        }

        if (timestamp == null || timestamp.isJsonNull()) {
            banner.setTimestamp("unknown");
        } else {
            banner.setTimestamp(timestamp.getAsString());
        }

        if (hostnames == null || hostnames.isJsonNull()) {
            banner.setHostnames(new String[0]);
        } else {
            JsonArray hostnamesAsJsonArray = hostnames.getAsJsonArray();
            String[] hostnameArray = new String[hostnamesAsJsonArray.size()];
            for (int i = 0; i < hostnamesAsJsonArray.size(); i++) {
                hostnameArray[i] = hostnamesAsJsonArray.get(i).getAsString();
            }
            banner.setHostnames(hostnameArray);
        }

        if (domains == null || domains.isJsonNull()) {
            banner.setDomains(new String[0]);
        } else {
            JsonArray domainsAsJsonArray = domains.getAsJsonArray();
            String[] domainsArray = new String[domainsAsJsonArray.size()];
            for (int i = 0; i < domainsAsJsonArray.size(); i++) {
                domainsArray[i] = domainsAsJsonArray.get(i).getAsString();
            }
            banner.setDomains(domainsArray);
        }

        if (location == null || location.isJsonNull()) {
            banner.setLocation(new Location());
        } else {
            JsonObject locationAsJsonObject = location.getAsJsonObject();
            JsonElement areaCode = locationAsJsonObject.get("area_code");
            JsonElement latitude = locationAsJsonObject.get("latitude");
            JsonElement longitude = locationAsJsonObject.get("longitude");
            JsonElement city = locationAsJsonObject.get("city");
            JsonElement regionCode = locationAsJsonObject.get("region_code");
            JsonElement postalCode = locationAsJsonObject.get("postal_code");
            JsonElement dmaCode = locationAsJsonObject.get("dma_code");
            JsonElement countryCode = locationAsJsonObject.get("country_code");
            JsonElement countryCode3 = locationAsJsonObject.get("country_code3");
            JsonElement countryName = locationAsJsonObject.get("country_name");

            Location locationObject = new Location();
            if (areaCode == null || areaCode.isJsonNull()) {
                locationObject.setAreaCode(0);
            } else {
                locationObject.setAreaCode(areaCode.getAsInt());
            }

            if (latitude == null || latitude.isJsonNull()) {
                locationObject.setLatitude(0.0);
            } else {
                locationObject.setLatitude(latitude.getAsDouble());
            }

            if (longitude == null || location.isJsonNull()) {
                locationObject.setLongitude(0.0);
            } else {
                locationObject.setLongitude(longitude.getAsDouble());
            }

            if (city == null || city.isJsonNull()) {
                locationObject.setCity("unknown");
            } else {
                locationObject.setCity(city.getAsString());
            }

            if (regionCode == null || regionCode.isJsonNull()) {
                locationObject.setRegionCode("unknown");
            } else {
                locationObject.setRegionCode(regionCode.getAsString());
            }

            if (postalCode == null || postalCode.isJsonNull()) {
                locationObject.setPostalCode("unknown");
            } else {
                locationObject.setPostalCode(postalCode.getAsString());
            }

            if (dmaCode == null || dmaCode.isJsonNull()) {
                locationObject.setDmaCode("unknown");
            } else {
                locationObject.setDmaCode(dmaCode.getAsString());
            }

            if (countryCode == null || countryCode.isJsonNull()) {
                locationObject.setCountryCode("unknown");
            } else {
                locationObject.setCountryCode(countryCode.getAsString());
            }

            if (countryCode3 == null || countryCode3.isJsonNull()) {
                locationObject.setCountryCode3("unknown");
            } else {
                locationObject.setCountryCode3(countryCode3.getAsString());
            }

            if (countryName == null || countryName.isJsonNull()) {
                locationObject.setCountryName("unknown");
            } else {
                locationObject.setCountryName(countryName.getAsString());
            }

            banner.setLocation(locationObject);
        }

        final Options opts = new Options();
        if (options == null || options.isJsonNull()) {
            opts.setRaw("unknown");
        } else {
            JsonObject object = options.getAsJsonObject();
            JsonElement raw = object.get("raw");
            if (raw == null || raw.isJsonNull()) {
                opts.setRaw("unknown");
            } else {
                opts.setRaw(raw.getAsString());
            }
        }
        banner.setOptions(opts);

        final Metadata shodanMetadata = new Metadata();
        if (metadata == null || metadata.isJsonNull()) {
            shodanMetadata.setCrawler("unknown");
            shodanMetadata.setId("unknown");
            shodanMetadata.setModule("unknown");
        } else {
            JsonObject metadataAsJsonObject = metadata.getAsJsonObject();
            JsonElement crawler = metadataAsJsonObject.get("crawler");
            JsonElement id = metadataAsJsonObject.get("id");
            JsonElement module = metadataAsJsonObject.get("module");

            if (crawler == null || crawler.isJsonNull()) {
                shodanMetadata.setCrawler("unknown");
            } else {
                shodanMetadata.setCrawler(crawler.getAsString());
            }

            if (id == null || id.isJsonNull()) {
                shodanMetadata.setId("unknown");
            } else {
                shodanMetadata.setId(id.getAsString());
            }

            if (module == null || module.isJsonNull()) {
                shodanMetadata.setModule("unknown");
            } else {
                shodanMetadata.setModule(module.getAsString());
            }
        }
        banner.setMetadata(shodanMetadata);

        final SslInfo sslInfo = new SslInfo();
        if (ssl == null || ssl.isJsonNull()) {
            banner.setSslEnabled(false);
        } else {
            banner.setSslEnabled(true);

            JsonObject sslAsJsonObject = ssl.getAsJsonObject();
            JsonElement chain = sslAsJsonObject.get("chain");
            JsonArray chainAsJsonArray = chain.getAsJsonArray();
            String[] chainArray = new String[chainAsJsonArray.size()];
            for (int i = 0; i < chainAsJsonArray.size(); i++) {
                chainArray[i] = chainAsJsonArray.get(i).getAsString();
            }
            sslInfo.setChain(chainArray);

            JsonElement versions = sslAsJsonObject.get("versions");
            JsonArray versionAsJsonArray = versions.getAsJsonArray();
            String[] versionsArray = new String[versionAsJsonArray.size()];
            for (int i = 0; i < versionsArray.length; i++) {
                versionsArray[i] = versionAsJsonArray.get(i).getAsString();
            }
            sslInfo.setVersions(versionsArray);

            JsonElement cipher = sslAsJsonObject.get("cipher");
            JsonObject cipherAsJsonObject = cipher.getAsJsonObject();
            JsonElement bits = cipherAsJsonObject.get("bits");
            JsonElement cipherVersion = cipherAsJsonObject.get("version");
            JsonElement name = cipherAsJsonObject.get("name");

            final Cipher cipherObject = new Cipher();
            if (bits != null && !bits.isJsonNull()) {
                cipherObject.setBits(bits.getAsInt());
            }
            if (cipherVersion != null && !cipherVersion.isJsonNull()) {
                cipherObject.setVersion(cipherVersion.getAsString());
            } else {
                cipherObject.setVersion("unknown");
            }
            if (name == null || name.isJsonNull()) {
                cipherObject.setName("unknown");
            } else {
                cipherObject.setName(name.getAsString());
            }
            sslInfo.setCipher(cipherObject);

            JsonElement dhparams = sslAsJsonObject.get("dhparams");
            if (dhparams != null && !dhparams.isJsonNull()) {
                JsonObject dhparamsAsJsonObject = dhparams.getAsJsonObject();

                JsonElement bits1 = dhparamsAsJsonObject.get("bits");
                JsonElement prime = dhparamsAsJsonObject.get("prime");
                JsonElement publicKey = dhparamsAsJsonObject.get("public_key");
                JsonElement generator = dhparamsAsJsonObject.get("generator");
                JsonElement fingerprint = dhparamsAsJsonObject.get("fingerprint");

                final DiffieHellmanParams diffieHellmanParams = new DiffieHellmanParams();
                if (bits1 != null && !bits1.isJsonNull()) {
                    diffieHellmanParams.setBits(bits1.getAsInt());
                }
                if (prime == null || prime.isJsonNull()) {
                    diffieHellmanParams.setPrime("unknown");
                } else {
                    diffieHellmanParams.setPrime(prime.getAsString());
                }
                if (publicKey == null || publicKey.isJsonNull()) {
                    diffieHellmanParams.setPublicKey("unknown");
                } else {
                    diffieHellmanParams.setPublicKey(publicKey.getAsString());
                }
                if (generator == null || generator.isJsonNull()) {
                    diffieHellmanParams.setGenerator("unknown");
                } else {
                    diffieHellmanParams.setGenerator(generator.getAsString());
                }
                if (fingerprint == null || fingerprint.isJsonNull()) {
                    diffieHellmanParams.setFingerprint("unknown");
                } else {
                    diffieHellmanParams.setFingerprint(fingerprint.getAsString());
                }
                sslInfo.setDiffieHellmanParams(diffieHellmanParams);
            }
        }
        banner.setSslInfo(sslInfo);

        if (uptime == null || uptime.isJsonNull()) {
            banner.setUptime(0);
        } else {
            banner.setUptime(uptime.getAsInt());
        }

        if (link == null || link.isJsonNull()) {
            banner.setLink("unknown");
        } else {
            banner.setLink(link.getAsString());
        }

        if (title == null || title.isJsonNull()) {
            banner.setTitle("unknown");
        } else {
            banner.setTitle(title.getAsString());
        }

        if (html == null || html.isJsonNull()) {
            banner.setHtml("unknown");
        } else {
            banner.setHtml(html.getAsString());
        }

        if (product == null || product.isJsonNull()) {
            banner.setProduct("unknown");
        } else {
            banner.setProduct(product.getAsString());
        }

        if (version == null || version.isJsonNull()) {
            banner.setVersion("unknown");
        } else {
            banner.setVersion(version.getAsString());
        }

        if (isp == null || isp.isJsonNull()) {
            banner.setIsp("unknown");
        } else {
            banner.setIsp(isp.getAsString());
        }

        if (os == null || os.isJsonNull()) {
            banner.setOs("unknown");
        } else {
            banner.setOs(os.getAsString());
        }

        if (transport == null || transport.isJsonNull()) {
            banner.setTransport("unknown");
        } else {
            banner.setTransport(transport.getAsString());
        }

        if (devicetype == null || devicetype.isJsonNull()) {
            banner.setDeviceType("unknown");
        } else {
            banner.setDeviceType(devicetype.getAsString());
        }

        if (info == null || info.isJsonNull()) {
            banner.setInfo("unknown");
        } else {
            banner.setInfo(info.getAsString());
        }

        if (cpe == null || cpe.isJsonNull()) {
            banner.setCpe(new String[0]);
        } else {
            // cpe can be string or string[]. Fix for #4
            if (cpe.isJsonObject()) {
                banner.setCpe(new String[] { cpe.getAsString() });

            } else {
                JsonArray cpeAsJsonArray = cpe.getAsJsonArray();
                String[] cpeArray = new String[cpeAsJsonArray.size()];
                for (int i = 0; i < cpeAsJsonArray.size(); i++) {
                    cpeArray[i] = cpeAsJsonArray.get(i).getAsString();
                }
                banner.setCpe(cpeArray);
            }
        }

        banners.add(banner);
    }
    return banners;
}

From source file:com.fooock.shodan.model.exploit.ExploitDeserializer.java

License:Open Source License

private Exploit parseJsonExploit(JsonElement json) {
    Exploit exploit = new Exploit();

    JsonObject jsonObject = json.getAsJsonObject();

    String id = jsonObject.get("_id").getAsString();
    String desc = jsonObject.get("description").getAsString();
    String source = jsonObject.get("source").getAsString();

    JsonElement jsonAuthor = jsonObject.get("author");
    if (jsonAuthor != null && !jsonAuthor.isJsonNull()) {
        if (jsonAuthor.isJsonPrimitive()) {
            String author = jsonAuthor.getAsString();
            exploit.setAuthor(author);/*from   w ww.j  a  v a  2s .  co m*/
        } else {
            JsonArray array = jsonAuthor.getAsJsonArray();
            if (array != null) {
                String resAuthors = "";
                for (JsonElement element : array) {
                    resAuthors += ", " + element.getAsString();
                }
                exploit.setAuthor(resAuthors);
            }
        }
    }

    JsonElement jsonCode = jsonObject.get("code");
    if (jsonCode != null && !jsonCode.isJsonNull()) {
        String code = jsonCode.getAsString();
        exploit.setCode(code);
    }

    JsonElement jsonType = jsonObject.get("type");
    if (jsonType != null && !jsonType.isJsonNull()) {
        String type = jsonType.getAsString();
        exploit.setType(type);
    }

    JsonElement jsonVersion = jsonObject.get("version");
    if (jsonVersion != null && !jsonVersion.isJsonNull()) {
        String version = jsonVersion.getAsString();
        exploit.setVersion(version);
    }

    JsonElement jsonPrivileged = jsonObject.get("privileged");
    if (jsonPrivileged != null && !jsonPrivileged.isJsonNull()) {
        boolean privileged = jsonPrivileged.getAsBoolean();
        exploit.setPrivileged(privileged);
    }

    JsonElement jsonPort = jsonObject.get("port");
    if (jsonPort != null && !jsonPort.isJsonNull()) {
        int port = jsonPort.getAsInt();
        exploit.setPort(port);
    }

    JsonArray jsonBid = jsonObject.getAsJsonArray("bid");
    if (jsonBid != null) {
        String[] bid = new String[jsonBid.size()];
        for (int i = 0; i < jsonBid.size(); i++) {
            bid[i] = jsonBid.get(i).getAsString();
        }
        exploit.setBid(bid);
    }

    JsonArray jsonCve = jsonObject.getAsJsonArray("cve");
    if (jsonCve != null) {
        String[] cve = new String[jsonCve.size()];
        for (int i = 0; i < jsonCve.size(); i++) {
            cve[i] = jsonCve.get(i).getAsString();
        }
        exploit.setCve(cve);
    }

    JsonArray jsonMsb = jsonObject.getAsJsonArray("msb");
    if (jsonMsb != null) {
        String[] msb = new String[jsonMsb.size()];
        for (int i = 0; i < jsonMsb.size(); i++) {
            msb[i] = jsonMsb.get(i).getAsString();
        }
        exploit.setMsb(msb);
    }

    JsonArray jsonOsvdb = jsonObject.getAsJsonArray("osvdb");
    if (jsonOsvdb != null) {
        String[] osvdb = new String[jsonOsvdb.size()];
        for (int i = 0; i < jsonOsvdb.size(); i++) {
            osvdb[i] = jsonOsvdb.get(i).getAsString();
        }
        exploit.setOsvdb(osvdb);
    }

    try {
        JsonArray jsonPlatform = jsonObject.getAsJsonArray("platform");
        if (jsonPlatform != null && jsonPlatform.isJsonArray()) {
            String[] platform = new String[jsonPlatform.size()];
            for (int i = 0; i < jsonPlatform.size(); i++) {
                platform[i] = jsonPlatform.get(i).getAsString();
            }
            exploit.setPlatform(platform);
        }
    } catch (ClassCastException err) {
        JsonElement platPrimitive = jsonObject.get("platform");
        if (platPrimitive != null && !platPrimitive.isJsonNull()) {
            exploit.setPlatform(new String[] { platPrimitive.getAsString() });
        }
    }

    exploit.setId(id);
    exploit.setDescription(desc);
    exploit.setSource(source);

    return exploit;
}

From source file:com.football.site.getdata.ScoreWebService.java

private static Leagues GetLeagueListFromWebService() {
    Leagues result = null;// w  ww  .  ja v a2 s. c  om
    try {
        JsonParser parser = new JsonParser();
        ArrayList<LeagueInfo> ligListe = new ArrayList<LeagueInfo>();
        String response = GetHttpClientResponse(
                "http://api.football-data.org/v1/soccerseasons"/*"http://www.football-data.org/alpha/soccerseasons"*/);
        JsonArray array = parser.parse(response).getAsJsonArray();
        LeagueInfo item = null;
        Gson gSon = new Gson();
        for (int i = 0; i < array.size(); i++) {
            item = gSon.fromJson(array.get(i).getAsJsonObject().toString(), LeagueInfo.class);
            ligListe.add(item);
        }
        result = new Leagues();
        result.setLeagueList(ligListe);

    } catch (Exception e) {
        HelperUtil.AddErrorLog(logger, e);
    }
    return result;
}

From source file:com.geecko.QuickLyric.lyrics.Genius.java

License:Open Source License

public static ArrayList<Lyrics> search(String query) {
    ArrayList<Lyrics> results = new ArrayList<>();
    query = Normalizer.normalize(query, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+",
            "");// ww  w  .  java2  s.  c om
    JsonObject response = null;
    try {
        URL queryURL = new URL(
                String.format("http://api.genius.com/search?q=%s", URLEncoder.encode(query, "UTF-8")));
        Connection connection = Jsoup.connect(queryURL.toExternalForm())
                .header("Authorization", "Bearer " + Keys.GENIUS).timeout(0).ignoreContentType(true);
        Document document = connection.userAgent(Net.USER_AGENT).get();
        response = new JsonParser().parse(document.text()).getAsJsonObject();
    } catch (JsonSyntaxException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (response == null || response.getAsJsonObject("meta").get("status").getAsInt() != 200)
        return results;
    JsonArray hits = response.getAsJsonObject("response").getAsJsonArray("hits");

    int processed = 0;
    while (processed < hits.size()) {
        JsonObject song = hits.get(processed).getAsJsonObject().getAsJsonObject("result");
        String artist = song.getAsJsonObject("primary_artist").get("name").getAsString();
        String title = song.get("title").getAsString();
        String url = "http://genius.com/songs/" + song.get("id").getAsString();
        Lyrics l = new Lyrics(Lyrics.SEARCH_ITEM);
        l.setArtist(artist);
        l.setTitle(title);
        l.setURL(url);
        l.setSource("Genius");
        results.add(l);
        processed++;
    }
    return results;
}

From source file:com.geecko.QuickLyric.lyrics.MetalArchives.java

License:Open Source License

@Reflection
public static Lyrics fromMetaData(String artist, String title) {
    String baseURL = "http://www.metal-archives.com/search/ajax-advanced/searching/songs/?bandName=%s&songTitle=%s&releaseType[]=1&exactSongMatch=1&exactBandMatch=1";
    String urlArtist = artist.replaceAll("\\s", "+");
    String urlTitle = title.replaceAll("\\s", "+");
    String url;/* w ww . java2 s. co  m*/
    String text;
    try {
        String response = Net.getUrlAsString(String.format(baseURL, urlArtist, urlTitle));
        JsonObject jsonResponse = new JsonParser().parse(response).getAsJsonObject();
        JsonArray track = jsonResponse.getAsJsonArray("aaData").get(0).getAsJsonArray();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < track.size(); i++)
            builder.append(track.get(i).getAsString());
        Document trackDocument = Jsoup.parse(builder.toString());
        url = trackDocument.getElementsByTag("a").get(1).attr("href");
        String id = trackDocument.getElementsByClass("viewLyrics").get(0).id().substring(11);
        text = Jsoup.connect("http://www.metal-archives.com/release/ajax-view-lyrics/id/" + id).get().body()
                .html();
    } catch (JsonParseException | IndexOutOfBoundsException e) {
        return new Lyrics(NO_RESULT);
    } catch (Exception e) {
        return new Lyrics(ERROR);
    }
    Lyrics lyrics = new Lyrics(POSITIVE_RESULT);
    lyrics.setArtist(artist);
    lyrics.setTitle(title);
    lyrics.setText(text);
    lyrics.setSource(domain);
    lyrics.setURL(url);

    return lyrics;
}

From source file:com.geecko.QuickLyric.MetalArchives.java

License:Open Source License

public static Lyrics fromMetaData(String artist, String title) {
    String baseURL = "http://www.metal-archives.com/search/ajax-advanced/searching/songs/?bandName=%s&songTitle=%s&releaseType[]=1&exactSongMatch=1&exactBandMatch=1";
    String urlArtist = artist.replaceAll("\\s", "+");
    String urlTitle = title.replaceAll("\\s", "+");
    String text;/*  w w  w . ja  va  2  s  .  c o  m*/
    try {
        String response = Net.getUrlAsString(String.format(baseURL, urlArtist, urlTitle));
        JsonObject jsonResponse = new JsonParser().parse(response).getAsJsonObject();
        JsonArray track = jsonResponse.getAsJsonArray("aaData").get(0).getAsJsonArray();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < track.size(); i++)
            builder.append(track.get(i).getAsString());
        Document trackDocument = Jsoup.parse(builder.toString());
        String id = trackDocument.getElementsByClass("viewLyrics").get(0).id().substring(11);
        text = Jsoup.connect("http://www.metal-archives.com/release/ajax-view-lyrics/id/" + id).get().body()
                .html();
    } catch (JsonParseException | IndexOutOfBoundsException e) {
        return new Lyrics(NO_RESULT);
    } catch (Exception e) {
        return new Lyrics(ERROR);
    }
    Lyrics lyrics = new Lyrics(POSITIVE_RESULT);
    lyrics.setText(text);

    return lyrics;
}

From source file:com.gemapps.saidit.networking.deserializer.TopEntriesDeserializer.java

License:Apache License

private JsonElement getFirstImage(JsonElement entryImages) {
    JsonArray imageSource = entryImages.getAsJsonObject().get("images").getAsJsonArray();
    return imageSource.get(0).getAsJsonObject().get("source");
}

From source file:com.getperka.flatpack.codexes.ArrayCodex.java

License:Apache License

@Override
public T[] readNotNull(JsonElement element, DeserializationContext context) throws Exception {
    JsonArray array = element.getAsJsonArray();
    @SuppressWarnings("unchecked")
    T[] toReturn = (T[]) Array.newInstance(elementType, array.size());
    for (int i = 0, j = array.size(); i < j; i++) {
        context.pushPath("[" + i + "]");
        toReturn[i] = valueCodex.read(array.get(i), context);
        context.popPath();/*  w w w.ja  va  2s.c  o  m*/
    }
    return toReturn;
}

From source file:com.ghjansen.cas.ui.desktop.swing.SimulationParameterJsonAdapter.java

License:Open Source License

public final T deserialize(final JsonElement elem, final Type interfaceType,
        final JsonDeserializationContext context) throws JsonParseException {
    final JsonObject member = (JsonObject) elem;
    final JsonObject ruleTypeParameterJson = member.getAsJsonObject("ruleTypeParameter");
    final JsonObject ruleConfigurationParameterJson = member.getAsJsonObject("ruleConfigurationParameter");
    final JsonArray stateValuesJson = ruleConfigurationParameterJson.get("stateValues").getAsJsonArray();
    final JsonObject limitsParameterJson = member.getAsJsonObject("limitsParameter");
    final JsonObject initialConditionParameterJson = member.getAsJsonObject("initialConditionParameter");
    final JsonArray sequencesJson = initialConditionParameterJson.get("sequences").getAsJsonArray();

    UnidimensionalRuleTypeParameter ruleTypeParameter = new UnidimensionalRuleTypeParameter(
            ruleTypeParameterJson.get("elementar").getAsBoolean());
    int[] stateValues = new int[stateValuesJson.size()];
    for (int i = 0; i < stateValuesJson.size(); i++) {
        stateValues[i] = stateValuesJson.get(i).getAsInt();
    }/*w ww . j  a va  2 s.c om*/
    UnidimensionalRuleConfigurationParameter ruleConfigurationParameter = new UnidimensionalRuleConfigurationParameter(
            stateValues[7], stateValues[6], stateValues[5], stateValues[4], stateValues[3], stateValues[2],
            stateValues[1], stateValues[0]);
    UnidimensionalLimitsParameter limitsParameter = new UnidimensionalLimitsParameter(
            limitsParameterJson.get("cells").getAsInt(), limitsParameterJson.get("iterations").getAsInt());
    UnidimensionalSequenceParameter sequences[] = new UnidimensionalSequenceParameter[sequencesJson.size()];
    for (int i = 0; i < sequencesJson.size(); i++) {
        JsonObject s = sequencesJson.get(i).getAsJsonObject();
        UnidimensionalSequenceParameter sequence = new UnidimensionalSequenceParameter(
                s.get("initialPosition").getAsInt(), s.get("finalPosition").getAsInt(),
                s.get("value").getAsInt());
        sequences[i] = sequence;
    }
    UnidimensionalInitialConditionParameter initialConditionParameter = new UnidimensionalInitialConditionParameter(
            sequences);
    try {
        return (T) new UnidimensionalSimulationParameter(ruleTypeParameter, ruleConfigurationParameter,
                limitsParameter, initialConditionParameter);
    } catch (InvalidSimulationParameterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:com.github.autermann.matlab.json.MatlabValueSerializer.java

License:Open Source License

private MatlabMatrix parseMatlabMatrix(JsonElement value) {
    JsonArray array = value.getAsJsonArray();
    double[][] values = new double[array.size()][array.get(0).getAsJsonArray().size()];
    for (int i = 0; i < array.size(); i++) {
        JsonArray innerArray = array.get(i).getAsJsonArray();
        for (int j = 0; j < innerArray.size(); j++) {
            values[i][j] = innerArray.get(j).getAsDouble();
        }// www. j  av  a  2  s  .  c  o  m
    }
    return new MatlabMatrix(values);
}