Example usage for org.json.simple.parser JSONParser JSONParser

List of usage examples for org.json.simple.parser JSONParser JSONParser

Introduction

In this page you can find the example usage for org.json.simple.parser JSONParser JSONParser.

Prototype

JSONParser

Source Link

Usage

From source file:data.GoogleBooksWS.java

@Override
public void parse(String tekst) throws Exception {

    //List<Book> lista=new ArrayList<>();

    JSONParser parser = new JSONParser();
    Object obj = parser.parse(tekst);
    JSONObject jsonObject = (JSONObject) obj;
    if (prvi) {//w  w  w.  j av a2  s  .  c  o  m
        int brojRezultata = Integer.parseInt(jsonObject.get("totalItems") + "");
        ukupanBrojStrana = brojRezultata / RESULTS_PER_PAGE + 1;
        System.out.println("Broj strana" + ukupanBrojStrana);
        prvi = false;
    }

    System.out.println("Trenutni broj strane " + trenutniBrojStrane);
    JSONArray niz = (JSONArray) jsonObject.get("items");
    if (niz == null) {
        kraj = true;
    } else {
        Iterator iterator = niz.iterator();
        while (iterator.hasNext()) {
            Book b = new Book();
            b.setUri(URIGenerator.generateUri(b));
            JSONObject book = (JSONObject) iterator.next();
            b.setTitle((String) ((JSONObject) book.get("volumeInfo")).get("title"));
            JSONArray autori = (JSONArray) ((JSONObject) book.get("volumeInfo")).get("authors");
            if (autori != null) {
                Iterator it = autori.iterator();
                while (it.hasNext()) {
                    Person p = new Person();
                    p.setUri(URIGenerator.generateUri(p));
                    p.setName((String) it.next());
                    b.getAuthors().add(p);
                }
            } else {
                System.out.println("Autori su null");
            }
            Organization o = new Organization();
            o.setUri(URIGenerator.generateUri(o));
            o.setName((String) ((JSONObject) book.get("volumeInfo")).get("publisher"));
            b.setPublisher(o);
            String date = (String) ((JSONObject) book.get("volumeInfo")).get("publishedDate");
            System.out.println(date);
            b.setDatePublished(date);

            String description = (String) ((JSONObject) book.get("volumeInfo")).get("description");
            b.setDescription(description);

            Object brStr = ((JSONObject) book.get("volumeInfo")).get("pageCount");
            if (brStr != null) {
                long broj = Long.parseLong(brStr.toString());
                b.setNumberOfPages((int) broj);
            }

            JSONArray identifiers = (JSONArray) ((JSONObject) book.get("volumeInfo"))
                    .get("industryIdentifiers");
            if (identifiers != null) {
                for (int i = 0; i < identifiers.size(); i++) {
                    JSONObject identifier = (JSONObject) identifiers.get(i);
                    if ("ISBN_13".equals((String) identifier.get("type"))) {
                        b.setIsbn((String) identifier.get("identifier"));
                    }
                }
            }
            //b.setIsbn((String) ((JSONObject) ((JSONArray)((JSONObject)book.get("volumeInfo")).get("industryIdentifiers")).get(1)).get("identifier"));

            lista.add(b);

        }

        if (trenutniBrojStrane < ukupanBrojStrana) {
            trenutniBrojStrane++;
        } else {
            kraj = true;
        }
    }
}

From source file:kjscompiler.Settings.java

public Settings(String path) throws ParseException, FileNotFoundException, IOException {
    JSONParser parser = new JSONParser();
    File file = new File(path);
    String parent = file.exists() ? file.getParent() : null;
    File dir = new File(null == parent || parent.isEmpty() ? "." : parent);
    FileReader fr = new FileReader(file);
    char[] fileData = new char[(int) file.length()];
    fr.read(fileData);/*from w  ww .j a v a  2s . co  m*/
    String content = new String(fileData);
    JSONObject obj = (JSONObject) parser.parse(content);
    if (obj.get("basedir") instanceof JSONArray) {
        this.baseDir = (JSONArray) obj.get("basedir");
    } else {
        JSONArray arr = new JSONArray();
        arr.add(obj.get("basedir"));
        this.baseDir = arr;
    }
    this.output = (String) obj.get("output");
    this.level = (String) obj.get("level");
    this.pattern = (String) obj.get("pattern");
    this.wrapper = obj.get("wrapper") != null ? (String) obj.get("wrapper") : "";
    this.projectPath = dir.getCanonicalPath();

    dir = new File(this.projectPath, this.output);
    this.output = dir.getCanonicalPath();

    fr.close();
}

From source file:edu.emory.library.viaf.ViafClient.java

/**
 * Query the VIAF AutoSuggest API to get suggestions matches for
 * a user-specified search term.  Returns an empty list if
 * no matches were found or if there was an error either making
 * the request or parsing the response./*  w  w  w . j  a  v a 2  s  .  c  o  m*/
 *
 * @param term  search term
 * @return      list of ViafResource
 */
public static List<ViafResource> suggest(String term) throws Exception {

    String uri = String.format("%s/AutoSuggest?query=%s", baseUrl, URLEncoder.encode(term, "UTF-8"));
    String result = EULHttpUtils.readUrlContents(uri);
    // todo: handle (at least log) http exceptions here

    List<ViafResource> resources = new ArrayList<ViafResource>();

    try {
        // parse the JSON and initialize a list of ViafResource objects
        // viaf autosuggest returns  in json format, with a list of results
        JSONObject json = (JSONObject) new JSONParser().parse(result);
        JSONArray jsonArray = (JSONArray) json.get("result");

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject obj = (JSONObject) jsonArray.get(i);

            // initialize a ViafResource for each result, using the viaf id and term
            // results may also include the following identifiers:
            //   lc, dnb, bnf, bne, nkc, nlilat, nla
            ViafResource vr = new ViafResource((String) obj.get("viafid"), (String) obj.get("term"));
            resources.add(vr);
        }

    } catch (Exception e) {
        // json parsing error - should just result in any empty resource list
        // TODO: log the error ?
    }
    return resources;
}

From source file:edu.pdx.konstan2.PortlandLive.responseParserFactory.java

public void parseVehiclesLocationJSON(String response, HashMap<LatLng, Vehicle> vMap) {
    try {/*  www  . j  av  a2  s .  c o  m*/
        JSONParser parser = new JSONParser();
        JSONObject jobj = (JSONObject) parser.parse(response.toString());
        JSONObject v = (JSONObject) jobj.get("resultSet");
        JSONArray arr = (JSONArray) v.get("vehicle");
        Iterator<JSONObject> iter = arr.iterator();
        while (iter.hasNext()) {
            Vehicle t = new Vehicle(iter.next());
            vMap.put(new LatLng(t.latitude, t.longitude), t);
        }
    } catch (Exception e) {
    }
}

From source file:clientserver.ServerThread.java

boolean receive() {
    JSONParser jParser = null;/*from www  . j av a2s . c o m*/
    String iJobj = null;
    JSONObject jReadobj = null;
    try {
        iJobj = br.readLine();
        jParser = new JSONParser();
        if (iJobj != null) {
            jReadobj = (JSONObject) jParser.parse(iJobj);
            System.out.println(
                    "Message from Client " + jReadobj.get("name") + ": " + (Long) jReadobj.get("value"));
            return true;
        } else {
            System.out.println("Read Socket closing");
            closeSocket();
            return false;
        }
    } catch (Exception e) {
        System.out.println("Read Socket closing" + e.getMessage());
        closeSocket();
        return false;
    }
}

From source file:interfaceTisseoWS.ST4.java

public final void init() throws ParseException, IOException, URISyntaxException {
    RequestJCDecaux r = new RequestJCDecaux();
    JSONParser parser = new JSONParser();

    r.setPathURIB("/vls/v1/stations");

    Object obj = parser.parse(r.request());
    JSONArray array = (JSONArray) obj;/*ww w .  j  ava  2  s . c  o m*/

    int nbStations = array.size();
    DefaultListModel lm = new DefaultListModel();
    for (int i = 0; i < nbStations; i++) {
        stations.add(new Station((JSONObject) array.get(i)));
        lm.addElement(stations.get(i).getName());
    }
    listeStations.setModel(lm);
}

From source file:edu.asu.msse.gnayak2.main.JSONFileReader.java

public JSONFileReader() {
    JSONParser jsonParser = new JSONParser();

    try {/*from   www.  jav a 2s . c om*/
        this.jsonArray = (JSONArray) jsonParser.parse(new FileReader(StringConstants.JSON_FILE_NAME));
    } catch (Exception e) {
        System.out.println("some ex");
    }
}

From source file:copter.WebSocketServerFactory.java

@Override
public void onMessage(WebSocket conn, String message) {

    JSONObject res = new JSONObject();
    String command = null;//from   w  w  w. j  a  v a2  s.  c o  m
    JSONObject jsonObj = null;
    try {
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(message);
        jsonObj = (JSONObject) obj;
        command = (String) jsonObj.get("command");

        if (command == null || command.isEmpty()) {
            return;
        }
        if (!command.equals(Constants.PING_COMMAND)) {
            logger.log("websocket message received: " + message);
        }
        switch (command) {
        case Constants.REBOOT_COMMAND:
            res.put("message", LinuxCommandsUtil.getInstance().rebootSystem());
            break;
        case Constants.CAMERA_COMMAND:
            res.put("message", CameraControl.getInstance().doAction(jsonObj));
            break;
        case Constants.GPS_COMMAND:
            res.put("message", GpsdConnector.getInstance().doAction(jsonObj, conn));
            break;
        case Constants.HCSR04_COMMAND:
            res.put("message", HCSR04.getInstance().doAction(jsonObj, conn));
            break;
        case Constants.MPU_COMMAND:
            res.put("message", MPU9150.getInstance().doAction(jsonObj, conn));
            break;
        case Constants.ENGINE_COMMAND:
            Engine.getInstance().doAction(jsonObj, conn);
            break;
        case Constants.GPIO_COMMAND:
            res.put("message", GpioControl.getInstance().doAction(jsonObj));
            break;
        case Constants.PING_COMMAND:
            res.put("status", "ok");
            String ping_id = (String) jsonObj.get("ping_id");
            res.put("ping_id", ping_id);
            break;
        default:
            res.put("message", "Unknown command '" + command + "'.");
            break;
        }

    } catch (Exception ex) {
        String err = "Json parse error: " + ex.getMessage();
        logger.log(err);
        res.put("message", err);
    }
    if (!res.isEmpty()) {
        conn.send(res.toJSONString());
        if (!command.equals(Constants.PING_COMMAND)) {
            logger.log("websocket response: " + res.toJSONString());
        }
    }
}

From source file:kltn.geocoding.Geocoding.java

private static Geometry getBoundary(String s)
        throws MalformedURLException, IOException, org.json.simple.parser.ParseException {
    String link = "https://maps.googleapis.com/maps/api/geocode/json?&key=AIzaSyALCgmmer3Cht-mFQiaJC9yoWdSqvfdAiM";
    link = link + "&address=" + URLEncoder.encode(s);
    URL url = new URL(link);
    HttpsURLConnection httpsCon = (HttpsURLConnection) url.openConnection();
    InputStream is = httpsCon.getInputStream();
    StringWriter writer = new StringWriter();
    IOUtils.copy(is, writer, "UTF-8");

    String jsonString = writer.toString();
    JSONParser parse = new JSONParser();
    Object obj = parse.parse(jsonString);
    JSONObject jsonObject = (JSONObject) obj;
    System.out.println(s);/*from w  w w.j  a  v  a  2 s  .com*/
    System.out.println(jsonObject.toJSONString());
    JSONArray resultArr = (JSONArray) jsonObject.get("results");
    Object resultObject = parse.parse(resultArr.get(0).toString());
    JSONObject resultJsonObject = (JSONObject) resultObject;

    Object geoObject = parse.parse(resultJsonObject.get("geometry").toString());
    JSONObject geoJsonObject = (JSONObject) geoObject;

    if (!geoJsonObject.containsKey("bounds")) {
        return null;
    }
    Object boundObject = parse.parse(geoJsonObject.get("bounds").toString());
    JSONObject boundJsonObject = (JSONObject) boundObject;
    //        System.out.println(boundJsonObject.toJSONString());

    Object southwest = parse.parse(boundJsonObject.get("southwest").toString());
    JSONObject southwestJson = (JSONObject) southwest;
    String southwestLat = southwestJson.get("lat").toString();
    String southwestLong = southwestJson.get("lng").toString();

    Object northeast = parse.parse(boundJsonObject.get("northeast").toString());
    JSONObject northeastJson = (JSONObject) northeast;
    String northeastLat = northeastJson.get("lat").toString();
    String northeastLong = northeastJson.get("lng").toString();

    String polygon = "POLYGON((" + southwestLong.trim() + " " + northeastLat.trim() + "," + northeastLong.trim()
            + " " + northeastLat.trim() + "," + northeastLong.trim() + " " + southwestLat.trim() + ","
            + southwestLong.trim() + " " + southwestLat.trim() + "," + southwestLong.trim() + " "
            + northeastLat.trim() + "))";
    Geometry geo = wktToGeometry(polygon);
    return geo;
}

From source file:interfaceTisseoWS.ST1.java

public void init() throws ParseException, IOException, URISyntaxException {
    RequestTisseo r = new RequestTisseo();
    JSONParser parser = new JSONParser();
    //recherche du lieu Univ. Paul Sabatier
    r.setPathURIB("/placesList");
    r.addParamURIB("term", "Univ. Paul Sabatier (Ut3) (TOULOUSE)");
    r.addParamURIB("displayOnlyStopAreas", "1");

    Object obj = parser.parse(r.request());
    JSONObject array = (JSONObject) obj;
    //recherche des arrts  Paul Sabatier
    r.resetURIB();//from  w ww.j av a2s.  co  m
    r.setPathURIB("/stopPointsList");
    r.addParamURIB("stopAreaId",
            (String) ((JSONObject) ((JSONArray) ((JSONObject) array.get("placesList")).get("place")).get(0))
                    .get("id"));
    r.addParamURIB("network", "Tisso");

    obj = parser.parse(r.request());
    array = (JSONObject) obj;
    int nbStops = ((JSONArray) ((JSONObject) array.get("physicalStops")).get("physicalStop")).size();
    int nbDeparts;
    Object obj2;
    JSONObject array2;
    for (int i = 0; i < nbStops; i++) {//boucle sur tous les arrts de Paul Sabatier
        r.resetURIB();
        r.setPathURIB("/departureBoard");
        r.addParamURIB("stopPointId",
                (String) ((JSONObject) ((JSONArray) ((JSONObject) array.get("physicalStops"))
                        .get("physicalStop")).get(i)).get("id"));
        obj2 = parser.parse(r.request());
        array2 = (JSONObject) obj2;

        nbDeparts = ((JSONArray) ((JSONObject) array2.get("departures")).get("departure")).size();
        if (nbDeparts > 1) {//si dpart trouv
            departs.add(new Depart((JSONObject) array2.get("departures")));
            listeLignes.addItem(departs.get(departs.size() - 1).toString());
        }
    }
}