Example usage for com.google.gson JsonParser parse

List of usage examples for com.google.gson JsonParser parse

Introduction

In this page you can find the example usage for com.google.gson JsonParser parse.

Prototype

@Deprecated
public JsonElement parse(JsonReader json) throws JsonIOException, JsonSyntaxException 

Source Link

Usage

From source file:com.adobe.acs.commons.json.JsonObjectUtil.java

License:Apache License

public static JsonObject toJsonObject(String json) {
    JsonParser parse = new JsonParser();
    return parse.parse(json).getAsJsonObject();
}

From source file:com.adobe.ags.curly.controller.DataImporterController.java

License:Apache License

private void openJson(File file) throws FileNotFoundException, IOException {
    FileReader fileReader = new FileReader(file);
    try (BufferedReader reader = new BufferedReader(fileReader)) {
        JsonParser parser = new JsonParser();
        JsonObject data = parser.parse(reader).getAsJsonObject();

        data.entrySet().stream().filter((entry) -> (entry.getValue().isJsonArray())).forEach((entry) -> {
            worksheetSelector.getItems().add(entry.getKey());
        });/*from   www. ja v a  2  s  . c  om*/

        sheetReader = (String node) -> readNodes(data.get(node).getAsJsonArray());
        skipFirstSelection.setValue(1);
        Platform.runLater(() -> worksheetSelector.getSelectionModel().selectFirst());
    }
}

From source file:com.adssets.api.Scout24.java

@Override
public String getApartments(String objectId) {
    try {/* w  w  w .j ava  2 s  .  c om*/
        // Make an API call... it is required to sign each request (see below)  
        //1276
        //            URL url = new URL("http://rest.immobilienscout24.de/restapi/api/search/v1.0/search/region?realestatetype=apartmentbuy&geocodes=" + regionid );
        URL url = new URL("https://rest.immobilienscout24.de/restapi/api/search/v1.0/expose/" + objectId);
        HttpURLConnection requestUrl = null;
        requestUrl = (HttpURLConnection) url.openConnection();

        consumer.sign(requestUrl);

        //            System.out.println("Sending request...");
        requestUrl.connect();

        //            System.out.println("Expiration " + requestUrl.getExpiration());
        //
        //            System.out.println("Timeout " + requestUrl.getConnectTimeout());
        //
        //            System.out.println("URL " + requestUrl.getURL());
        //
        //            System.out.println("Method " + requestUrl.getRequestMethod());
        //
        //            System.out.println("Response: " + requestUrl.getResponseCode() + " " + requestUrl.getResponseMessage());
        BufferedReader br = new BufferedReader(new InputStreamReader(requestUrl.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;

        switch (requestUrl.getResponseCode()) {
        case 200:
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();

            try {

                JSONObject outObj = XML.toJSONObject(sb.toString());
                JsonParser parser = new JsonParser();

                Object objPrice = new Object();
                JsonObject objPriceJson = new JsonObject();
                //                        JSONObject objTitlePicture = new JSONObject();
                JSONArray objAllPictures = new JSONArray();
                JSONObject objAdPicture = new JSONObject();
                JSONObject objAddress = new JSONObject();
                Object objPricem2 = new Object();
                JsonObject objPricem2Json = new JsonObject();
                JSONObject objLivingspace = new JSONObject();
                JSONObject obj = new JSONObject();

                //                        System.out.println(outObj.toString());
                objPrice = outObj.getJSONObject("expose:expose").getJSONObject("realEstate")
                        .get("calculatedPrice"); //price

                objPriceJson = parser.parse(objPrice.toString()).getAsJsonObject();

                //                        objTitlePicture = outObj.getJSONObject("expose:expose").getJSONObject("realEstate").getJSONObject("titlePicture").getJSONObject("urls")
                //                                .getJSONArray("url").getJSONObject(1);
                objAllPictures = outObj.getJSONObject("expose:expose").getJSONObject("realEstate")
                        .getJSONObject("attachments").getJSONArray("attachment");
                objAdPicture = outObj.getJSONObject("expose:expose").getJSONObject("realEstate")
                        .getJSONObject("titlePicture").getJSONObject("urls").getJSONArray("url")
                        .getJSONObject(4);
                objAddress = outObj.getJSONObject("expose:expose").getJSONObject("realEstate")
                        .getJSONObject("address");

                objPricem2 = outObj.getJSONObject("expose:expose").getJSONObject("realEstate").get("price");
                objPricem2Json = parser.parse(objPricem2.toString()).getAsJsonObject();

                obj.put("price", objPrice);
                obj.put("allpictures", objAllPictures);
                obj.put("adpicture", objAdPicture);
                obj.put("address", objAddress);
                obj.put("livingspace",
                        (int) Math.round((Double.parseDouble(objPriceJson.get("value").getAsString())
                                / Double.parseDouble(objPricem2Json.get("value").getAsString()))));

                return obj.toString(); //obj
            } catch (JSONException je) {
                je.printStackTrace();
                return "{\"error\":2}";
            }
        case 201:
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();

            try {
                JSONObject outObj = XML.toJSONObject(sb.toString());
                return outObj.toString();
            } catch (JSONException je) {
                je.printStackTrace();
                return "{\"error\":2}";

            }
        }

    } catch (Exception e) {
        System.out.println("-------REMOVE OBJECT------");

        e.printStackTrace();
        return "{\"error\":1}";

    }

    return "{\"error\":1}";
}

From source file:com.adssets.api.Scout24.java

@Override
public String getLoans(String postalcode, String suburb) {
    try {//w  w  w.j ava2s .  co m
        // Make an API call... it is required to sign each request (see below)  
        Boolean getGeoCode = false;
        URL url;
        if (postalcode != null) {
            url = new URL(
                    "http://rest.immobilienscout24.de/restapi/api/financing/construction/v2/offer?postalcode="
                            + postalcode);
        } else if (suburb != null) {
            getGeoCode = true;
            suburb = suburb.replace("_", "*");
            url = new URL("https://rest.immobilienscout24.de/restapi/api/search/v1.0/region?q=" + suburb);
        } else {
            url = new URL("http://rest.immobilienscout24.de/restapi/api/financing/construction/v2/offer");
        }

        HttpURLConnection requestUrl = null;
        requestUrl = (HttpURLConnection) url.openConnection();
        consumer.sign(requestUrl);
        requestUrl.connect();

        BufferedReader br = new BufferedReader(new InputStreamReader(requestUrl.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;

        switch (requestUrl.getResponseCode()) {
        case 200:
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();

            try {
                JsonParser parser = new JsonParser();

                JsonObject outObj = parser.parse(sb.toString()).getAsJsonObject();
                //If a suburb is sent, get the geocode for that suburb
                if (getGeoCode) {
                    System.out.println("GETGEOCODE");
                    //Get geoCodeId
                    System.out.println(outObj.toString());
                    String geoCodeId = outObj.get("region.regions").getAsJsonArray().get(0).getAsJsonObject()
                            .get("region").getAsJsonArray().get(0).getAsJsonObject().get("geoCodeId")
                            .getAsString();

                    System.out.println(geoCodeId);
                    //1276003001003  1276003001 
                    url = new URL(
                            "http://rest.immobilienscout24.de/restapi/api/financing/construction/v2/offer?geocode="
                                    + geoCodeId);
                    requestUrl = null;
                    requestUrl = (HttpURLConnection) url.openConnection();
                    consumer.sign(requestUrl);
                    requestUrl.connect();
                    br = new BufferedReader(new InputStreamReader(requestUrl.getInputStream()));
                    sb = new StringBuilder();
                    while ((line = br.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    outObj = parser.parse(sb.toString()).getAsJsonObject();
                    return sortData(outObj);

                } else {

                    return sortData(outObj);
                }

            } catch (JSONException je) {
                je.printStackTrace();
                return "{\"error\":2}";
            }
        case 201:
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();

            try {
                JSONObject outObj = XML.toJSONObject(sb.toString());
                return outObj.toString();
            } catch (JSONException je) {
                je.printStackTrace();
                return "{\"error\":2}";

            }
        }

    } catch (Exception e) {

        e.printStackTrace();

    }

    return "{\"error\":1}";
}

From source file:com.adssets.ejb.DataAccess.java

@Override
public String buildFeedForMarket(String marketId, String lazyLoad) {
    JsonArray jsonArray = new JsonArray();
    JsonParser parser = new JsonParser();

    //        Feed feed = feedFacade.find(marketId);
    Market market = marketFacade.find(Integer.valueOf(marketId));

    List<Feed> feeds = em.createNamedQuery("Feed.findByMarketId").setParameter("marketId", market)
            .getResultList();/*ww w.  ja  v a2s.c o  m*/
    if (feeds.size() > 0) {
        for (Feed feed : feeds) {
            JsonObject obj = new JsonObject();
            obj.addProperty("id", feed.getId());
            obj.addProperty("marketId", feed.getIdmarket().getId());
            obj.addProperty("json", feed.getJson());
            jsonArray.add(obj);
        }

        JsonObject obj = jsonArray.get(0).getAsJsonObject();
        String objArray = obj.get("json").getAsString();

        JsonArray objArrayParsed = parser.parse(objArray).getAsJsonArray();
        JsonArray objData = new JsonArray();

        for (JsonElement objId : objArrayParsed) {
            JsonObject objElmParsed = parser.parse(objId.toString()).getAsJsonObject();
            System.out.println(objElmParsed);
            //            try{
            //            isInteger(objId.getAsString());
            String value = objElmParsed.get("type").getAsString();
            System.out.println(value);
            //CHANGE ADPICTURE TO THE PICTURE STORED IN THE DATABASE
            if (value.equals("object")) {
                String result = scout24.getApartments(objElmParsed.get("objectid").getAsString());
                if (!result.equals("{\"error\":1}")) {
                    JsonObject resultObj = parser.parse(result).getAsJsonObject();
                    String link = "{\"link\": \"https://www.immobilienscout24.de/expose/"
                            + objElmParsed.get("objectid").getAsInt() + "?referrer=\"}";
                    JsonObject clickLink = parser.parse(link).getAsJsonObject();
                    resultObj.add("clickLink", clickLink);
                    resultObj.add("objectId", objElmParsed.get("objectid"));
                    resultObj.add("marketId", parser.parse(marketId));
                    // Use the selected image as ad image
                    JsonObject objHref = new JsonObject();
                    objHref.add("href", objElmParsed.get("url"));
                    resultObj.add("adpicture", objHref);
                    //If lazyLoad = yes dont return "allpictures" LazyLoad=yes is the parameter the ad will send so it does not get unneccesary data
                    if (lazyLoad.equals("yes")) {
                        resultObj.remove("allpictures");
                    }

                    objData.add(resultObj);
                }

            } else {
                objData.add(objId);
            }
            //            }catch(UnsupportedOperationException ex){
            //            objData.add(objId);
            //            }

        }
        return objData.toString();
    } else {
        return new JsonArray().toString();
    }

}

From source file:com.agateau.pixelwheels.stats.JsonGameStatsIO.java

License:Open Source License

@Override
public void load() {
    Assert.check(mGameStats != null, "setGameStats() has not been called");
    if (!mHandle.exists()) {
        return;/*from w w  w  .  j  av a2s . c om*/
    }
    mGameStats.mTrackStats.clear();
    String json = mHandle.readString("UTF-8");
    JsonParser parser = new JsonParser();
    JsonObject root = parser.parse(json).getAsJsonObject();
    JsonObject trackStatsObject = root.getAsJsonObject("trackStats");
    for (Map.Entry<String, JsonElement> kv : trackStatsObject.entrySet()) {
        String trackId = kv.getKey();
        mGameStats.addTrack(trackId);
        loadTrackStats(mGameStats.getTrackStats(trackId), kv.getValue().getAsJsonObject());
    }
}

From source file:com.aliyun.odps.udf.utils.CounterUtils.java

License:Apache License

/**
 * JSON{@link Counters}/*  w w  w. ja  v a2 s.  c  o  m*/
 *  {@link RuntimeException}
 *
 * @param json
 *     JSON
 * @return {@link Counters}
 * @see #toJsonString(Counters)
 */
public static Counters createFromJsonString(String json) {
    JsonParser parser = new JsonParser();
    JsonElement el = parser.parse(json);
    return createFromJson(el.getAsJsonObject());
}

From source file:com.amazonaws.apigatewaydemo.RequestRouter.java

License:Open Source License

/**
 * The main Lambda function handler. Receives the request as an input stream, parses the json and looks for the
 * "action" property to decide where to route the request. The "body" property of the incoming request is passed
 * to the DemoAction implementation as a request body.
 *
 * @param request  The InputStream for the incoming event. This should contain an "action" and "body" properties. The
 *                 action property should contain the namespaced name of the class that should handle the invocation.
 *                 The class should implement the DemoAction interface. The body property should contain the full
 *                 request body for the action class.
 * @param response An OutputStream where the response returned by the action class is written
 * @param context  The Lambda Context object
 * @throws BadRequestException    This Exception is thrown whenever parameters are missing from the request or the action
 *                                class can't be found
 * @throws InternalErrorException This Exception is thrown when an internal error occurs, for example when the database
 *                                is not accessible
 *//*from   w ww .j ava  2  s  .c  o  m*/
public static void lambdaHandler(InputStream request, OutputStream response, Context context)
        throws BadRequestException, InternalErrorException {
    LambdaLogger logger = context.getLogger();

    JsonParser parser = new JsonParser();
    JsonObject inputObj;
    try {
        inputObj = parser.parse(IOUtils.toString(request)).getAsJsonObject();
    } catch (IOException e) {
        logger.log("Error while reading request\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    }

    if (inputObj == null || inputObj.get("action") == null
            || inputObj.get("action").getAsString().trim().equals("")) {
        logger.log("Invald inputObj, could not find action parameter");
        throw new BadRequestException("Could not find action value in request");
    }

    String actionClass = inputObj.get("action").getAsString();
    DemoAction action;

    try {
        action = DemoAction.class.cast(Class.forName(actionClass).newInstance());
    } catch (final InstantiationException e) {
        logger.log("Error while instantiating action class\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    } catch (final IllegalAccessException e) {
        logger.log("Illegal access while instantiating action class\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    } catch (final ClassNotFoundException e) {
        logger.log("Action class could not be found\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    }

    if (action == null) {
        logger.log("Action class is null");
        throw new BadRequestException("Invalid action class");
    }

    JsonObject body = null;
    if (inputObj.get("body") != null) {
        body = inputObj.get("body").getAsJsonObject();
    }

    String output = action.handle(body, context);

    try {
        IOUtils.write(output, response);
    } catch (final IOException e) {
        logger.log("Error while writing response\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    }
}

From source file:com.android.cloudfiles.cloudfilesforandroid.CloudFiles.java

License:Apache License

private void authentication(String userName, String apiKey) throws IOException {
    String json = generateToken(userName, apiKey);

    JsonParser jsonParser = new JsonParser();
    JsonObject jo = (JsonObject) jsonParser.parse(json);

    setToken(jo.getAsJsonObject("access").getAsJsonObject("generateToken").get("id").getAsString());
    JsonArray services = jo.getAsJsonObject("access").get("serviceCatalog").getAsJsonArray();

    for (JsonElement jsonElement : services) {
        JsonObject jobj = jsonElement.getAsJsonObject();

        if (jobj.get("name").getAsString().equals("cloudFiles")) {

            JsonArray endpoints = jobj.getAsJsonArray("endpoints");
            for (JsonElement jsonElement2 : endpoints) {

                urls.put(jsonElement2.getAsJsonObject().get("region").getAsString(),
                        jsonElement2.getAsJsonObject().get("publicURL").getAsString());

            }//from  w w  w .java2s  .  co m
        }

        if (jobj.get("name").getAsString().equals("cloudFilesCDN")) {

            JsonArray endpoints = jobj.getAsJsonArray("endpoints");
            for (JsonElement jsonElement2 : endpoints) {

                cdnUrls.put(jsonElement2.getAsJsonObject().get("region").getAsString(),
                        jsonElement2.getAsJsonObject().get("publicURL").getAsString());

            }
        }

    }

}

From source file:com.android.tools.idea.gradle.structure.model.repositories.search.JCenterRepository.java

License:Apache License

SearchResult parse(@NotNull Reader response) {
    /*//from w  w  w  .  ja  va2  s.  co  m
      Sample response:
      [
        {
          "name": "com.atlassian.guava:guava",
          "repo": "jcenter",
          "owner": "bintray",
          "desc": null,
          "system_ids": [
    "com.atlassian.guava:guava"
          ],
          "versions": [
    "15.0"
          ],
          "latest_version": "15.0"
        },
        {
          "name": "com.atlassian.bundles:guava",
          "repo": "jcenter",
          "owner": "bintray",
          "desc": null,
          "system_ids": [
    "com.atlassian.bundles:guava"
          ],
          "versions": [
    "8.1",
    "8.0",
    "1.0-actually-8.1"
          ],
          "latest_version": "8.1"
        },
        {
          "name": "io.janusproject.guava:guava",
          "repo": "jcenter",
          "owner": "bintray",
          "desc": null,
          "system_ids": [
    "io.janusproject.guava:guava"
          ],
          "versions": [
    "19.0.0",
    "17.0.2",
    "17.0"
          ],
          "latest_version": "19.0.0"
        },
        {
          "name": "com.google.guava:guava",
          "repo": "jcenter",
          "owner": "bintray",
          "desc": "Guava is a suite of core and expanded libraries that include\n    utility classes, google's collections, io classes, and much\n    much more.\n\n    Guava has two code dependencies - javax.annotation\n    per the JSR-305 spec and javax.inject per the JSR-330 spec.",
          "system_ids": [
    "com.google.guava:guava"
          ],
          "versions": [
    "19.0",
    "19.0-rc3",
    "19.0-rc2",
    "19.0-rc1",
    "18.0",
    "18.0-rc2",
    "18.0-rc1",
    "11.0.2-atlassian-02",
    "17.0",
    "17.0-rc2",
    "17.0-rc1",
    "16.0.1",
    "16.0",
    "16.0-rc1",
    "15.0",
    "15.0-rc1",
    "14.0.1",
    "14.0",
    "14.0-rc3",
    "14.0-rc2",
    "14.0-rc1",
    "13.0.1",
    "13.0",
    "13.0-final",
    "13.0-rc2",
    "13.0-rc1",
    "12.0.1",
    "12.0",
    "12.0-rc2",
    "12.0-rc1",
    "11.0.2-atlassian-01",
    "11.0.2",
    "11.0.1",
    "11.0",
    "11.0-rc1",
    "10.0.1",
    "10.0",
    "10.0-rc3",
    "10.0-rc2",
    "10.0-rc1",
    "r09",
    "r08",
    "r07",
    "r06",
    "r05",
    "r03"
          ],
          "latest_version": "19.0"
        }
      ]
     */

    JsonParser parser = new JsonParser();
    JsonArray array = parser.parse(response).getAsJsonArray();

    int totalFound = array.size();
    List<FoundArtifact> artifacts = Lists.newArrayListWithExpectedSize(totalFound);

    for (int i = 0; i < totalFound; i++) {
        JsonObject root = array.get(i).getAsJsonObject();
        String name = root.getAsJsonPrimitive("name").getAsString();

        List<GradleVersion> availableVersions = Lists.newArrayList();
        JsonArray versions = root.getAsJsonArray("versions");
        versions.forEach(element -> {
            String version = element.getAsString();
            availableVersions.add(GradleVersion.parse(version));
        });

        List<String> coordinate = Splitter.on(GRADLE_PATH_SEPARATOR).splitToList(name);
        assert coordinate.size() == 2;

        artifacts.add(new FoundArtifact(getName(), coordinate.get(0), coordinate.get(1), availableVersions));
    }

    return new SearchResult(getName(), artifacts, totalFound);
}