Example usage for javax.json JsonObject getJsonArray

List of usage examples for javax.json JsonObject getJsonArray

Introduction

In this page you can find the example usage for javax.json JsonObject getJsonArray.

Prototype

JsonArray getJsonArray(String name);

Source Link

Document

Returns the array value to which the specified name is mapped.

Usage

From source file:Main.java

public static void main(String[] args) {
    String personJSONData = "  {" + "   \"name\": \"Jack\", " + "   \"age\" : 13, "
            + "   \"isMarried\" : false, " + "   \"address\": { " + "     \"street\": \"#1234, Main Street\", "
            + "     \"zipCode\": \"123456\" " + "   }, "
            + "   \"phoneNumbers\": [\"011-111-1111\", \"11-111-1111\"] " + " }";

    JsonReader reader = Json.createReader(new StringReader(personJSONData));

    JsonObject personObject = reader.readObject();

    reader.close();/* w ww .j a  v  a2 s. co m*/

    System.out.println("Name   : " + personObject.getString("name"));
    System.out.println("Age    : " + personObject.getInt("age"));
    System.out.println("Married: " + personObject.getBoolean("isMarried"));

    JsonObject addressObject = personObject.getJsonObject("address");
    System.out.println("Address: ");
    System.out.println(addressObject.getString("street"));
    System.out.println(addressObject.getString("zipCode"));

    System.out.println("Phone  : ");
    JsonArray phoneNumbersArray = personObject.getJsonArray("phoneNumbers");
    for (JsonValue jsonValue : phoneNumbersArray) {
        System.out.println(jsonValue.toString());
    }
}

From source file:org.jboss.set.aphrodite.stream.services.json.StreamComponentJsonParser.java

private static List<String> getContacts(JsonObject json) {
    final JsonArray contactsArray = json.getJsonArray(JSON_CONTACTS);
    final List<String> contacts = new ArrayList<>(contactsArray.size());
    for (int index = 0; index < contactsArray.size(); index++) {
        contacts.add(contactsArray.getString(index));
    }//from   w ww.ja  v  a  2s  .c o  m
    return contacts;
}

From source file:org.json.StackExchangeAPI.java

private static void parseStackExchange(String jsonStr) {
    JsonReader reader = null;/*from w  w w . j a va2s. co m*/
    try {
        reader = Json.createReader(new StringReader(jsonStr));
        JsonObject jsonObject = reader.readObject();
        reader.close();
        JsonArray array = jsonObject.getJsonArray("items");
        for (JsonObject result : array.getValuesAs(JsonObject.class)) {

            JsonObject ownerObject = result.getJsonObject("owner");
            // int ownerReputation = ownerObject.getInt("reputation");
            //  System.out.println("Reputation:"+ownerReputation);
            int viewCount = result.getInt("view_count");
            System.out.println("View Count :" + viewCount);
            int answerCount = result.getInt("answer_count");
            System.out.println("Answer Count :" + answerCount);
            String link = result.getString("link");
            System.out.println("URL: " + link);
            String title = result.getString("title");
            System.out.println("Title: " + title);
            String body = result.getString("body");
            System.out.println("Body: " + body);
            JsonArray tagsArray = result.getJsonArray("tags");
            StringBuilder tagBuilder = new StringBuilder();
            int i = 1;
            for (JsonValue tag : tagsArray) {
                tagBuilder.append(tag.toString());
                if (i < tagsArray.size())
                    tagBuilder.append(",");
                i++;
            }

            System.out.println("Tags: " + tagBuilder.toString());
            System.out.println("------------------------------------------");
        }

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

From source file:org.jboss.set.aphrodite.stream.services.json.StreamsJsonParser.java

public static Map<String, Stream> parse(final URL url) throws NotFoundException {
    try (InputStream is = url.openStream()) {
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        JsonReader jr = Json.createReader(rd);

        final JsonArray jsonArray = jr.readObject().getJsonArray(JSON_STREAMS);
        Objects.requireNonNull(jsonArray, "streams array must be specified in json file");
        final Map<String, Stream> streamMap = new LinkedHashMap<String, Stream>();
        for (JsonValue value : jsonArray) {
            JsonObject json = (JsonObject) value;

            String upstreamName = json.getString(JSON_UPSTREAM, null);
            Stream upstream = streamMap.get(upstreamName);

            JsonArray codebases = json.getJsonArray(JSON_CODEBASES);
            Map<String, StreamComponent> codebaseMap = parseStreamCodebases(codebases);

            Stream currentStream = new Stream(url, json.getString(JSON_NAME), upstream, codebaseMap);
            streamMap.put(currentStream.getName(), currentStream);
        }//from   w ww.  j a  v a2 s.com
        return streamMap;
    } catch (Exception e) {
        Utils.logException(LOG, "Unable to load url: " + url.toString(), e);
        throw new NotFoundException(e);
    }
}

From source file:at.porscheinformatik.sonarqube.licensecheck.maven.MavenDependencyScanner.java

private static void parseDependencyJson(Set<Dependency> dependencies, JsonArray jsonDependencyArray) {
    for (int i = 0; i < jsonDependencyArray.size(); i++) {
        JsonObject jsonDependency = jsonDependencyArray.getJsonObject(i);
        String scope = jsonDependency.getString("s");
        if ("compile".equals(scope) || "runtime".equals(scope)) {
            if (jsonDependency.containsKey("d")) {
                parseDependencyJson(dependencies, jsonDependency.getJsonArray("d"));
            }//w  w w  .  ja  v  a 2s  . c  o  m

            Dependency dependency = new Dependency(jsonDependency.getString("k"), jsonDependency.getString("v"),
                    null);
            dependencies.add(dependency);
        }
    }
}

From source file:com.buffalokiwi.aerodrome.jet.JetAPIResponse.java

/**
 * Check the response body for errors/*from  w ww  .j  av  a 2 s .  co m*/
 * @param res JSON results
 * @throws JetException if there's an issue
 */
public static final void checkErrors(final JsonObject res, final IAPIResponse apiRes) throws JetException {
    if (res.containsKey("errors")) {
        final JsonArray errors = res.getJsonArray("errors");
        ArrayList<String> messages = new ArrayList<>();

        for (int i = 0; i < errors.size(); i++) {
            messages.add(errors.getString(i, ""));
        }

        throw new JetException(messages, null, apiRes);
    } else if (res.containsKey("error")) {
        throw new JetException(res.getString("error"), null, apiRes);
    }
}

From source file:com.buffalokiwi.aerodrome.jet.products.ProductVariationGroupRec.java

/**
 * Create a new JetProductVariationGroup instance based on Jet JSON.
 * @param sku The parent sku that was queried 
 * @param json JSON response from jet product variation query.
 * @return object/*from w w  w  . j av a  2s  . c o m*/
 * @throws IllegalArgumentException if sku or json are null/empty
 * @throws ClassCastException if Any array items are of an incorrect type
 */
public static ProductVariationGroupRec fromJSON(final String sku, final JsonObject json)
        throws IllegalArgumentException, ClassCastException {
    Utils.checkNullEmpty(sku, "sku");
    Utils.checkNull(json, "json");

    final List<String> childSkus = new ArrayList<>();
    final JsonArray skus = json.getJsonArray("children_skus");
    if (skus != null) {
        for (int i = 0; i < skus.size(); i++) {
            final JsonObject entry = skus.getJsonObject(i);
            if (entry != null) {
                final String child = entry.getString("merchant_sku", "");
                if (!child.isEmpty())
                    childSkus.add(child);
            }
        }
    }

    return new ProductVariationGroupRec(sku, Relationship.byText(json.getString("relationship", "")),
            Utils.jsonArrayToLongList(json.getJsonArray("variation_refinements")), childSkus,
            json.getString("group_title", ""));
}

From source file:com.natixis.appdynamics.traitements.GetInfoLicense.java

public Map<String, Object> RetrieveInfoLicense() throws ClientProtocolException, IOException {
    Map<String, Object> myMapInfoLicense = new HashMap<String, Object>();

    HttpClient client = new DefaultHttpClient();

    String[] chaineUrl = GetParamApplication.urlApm.split("/" + "/");
    String hostApm = chaineUrl[1];

    URI uri = null;/*  ww  w  .  j  a  v  a  2 s  .  co  m*/
    try {
        uri = new URIBuilder().setScheme("http").setHost(hostApm).setPath(GetParamApplication.uriInfoLicense)
                .setParameter("startdate", GetDateInfoLicence()).setParameter("enddate", GetDateInfoLicence())
                .build();
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    ((DefaultHttpClient) client).getCredentialsProvider().setCredentials(new AuthScope(hostApm, 80),
            new UsernamePasswordCredentials(GetParamApplication.userApm, GetParamApplication.passwordApm));
    HttpGet request = new HttpGet(uri);
    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();
    String jsonContent = EntityUtils.toString(entity);
    Reader stringReader = new StringReader(jsonContent);
    JsonReader rdr = Json.createReader(stringReader);
    JsonObject obj = rdr.readObject();
    JsonArray results = obj.getJsonArray("usages");

    for (JsonObject result : results.getValuesAs(JsonObject.class)) {
        BeanInfoLicense myBeanInfoLicense = new BeanInfoLicense(result.getString("agentType"),
                result.getInt("avgUnitsAllowed"), result.getInt("avgUnitsUsed"));
        myMapInfoLicense.put(result.getString("agentType"), myBeanInfoLicense);
        //System.out.println(result.getString("agentType")+","+result.getInt("avgUnitsAllowed")+","+result.getInt("avgUnitsUsed"));
    }

    return myMapInfoLicense;
}

From source file:GUI_The_Code_Book.ParserAPIStackEx.java

private void parseStackExchange(String jsonStr) {
    JsonReader reader = null;//from www . j  a  v  a 2 s  . c o  m
    try {
        reader = Json.createReader(new StringReader(jsonStr));
        JsonObject jsonObject = reader.readObject();
        reader.close();
        JsonArray array = jsonObject.getJsonArray("items");
        for (JsonObject result : array.getValuesAs(JsonObject.class)) {
            urlList.add(new URLlist(result.getInt("view_count"), result.getInt("answer_count"),
                    result.getString("title"), result.getString("link")));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:uk.ac.ebi.ep.data.service.BioPortalService.java

@Transactional
public String getDiseaseDescription(String term) {
    String definition = "";

    // Reader reader = new StringReader(get(REST_URL + "/search?q=" + term+"&ontology={EFO,MeSH,OMIM}&exact_match=true"));
    Reader reader = new StringReader(get(REST_URL + "/search?q=" + term));

    JsonReader jsonReader = Json.createReader(reader);

    JsonObject jo = jsonReader.readObject();

    JsonArray jsonArray = jo.getJsonArray("collection");
    for (JsonObject obj : jsonArray.getValuesAs(JsonObject.class)) {

        for (Map.Entry<String, JsonValue> entry : obj.entrySet()) {

            if (entry.getKey().equalsIgnoreCase(DEFINITION)) {

                definition = entry.getValue().toString().replace("\"", "").replaceAll("\\[", "")
                        .replaceAll("\\]", "");
            }/*from w ww . j a va 2s. com*/

        }
    }

    return definition;
}