Example usage for org.json.simple JSONValue parseWithException

List of usage examples for org.json.simple JSONValue parseWithException

Introduction

In this page you can find the example usage for org.json.simple JSONValue parseWithException.

Prototype

public static Object parseWithException(String s) throws ParseException 

Source Link

Usage

From source file:bonapetit.ParseJson1.java

public static void main(String[] args) {
    String url = "http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2";
    /*/*from  w w  w . java  2  s  .  c o m*/
     * {"title":"Free Music Archive - Genres","message":"","errors":[],"total" : "161","total_pages":81,"page":1,"limit":"2",
     * "dataset":
     * [{"genre_id": "1","genre_parent_id":"38","genre_title":"Avant-Garde" ,"genre_handle": "Avant-Garde","genre_color":"#006666"},
     * {"genre_id":"2","genre_parent_id" :null,"genre_title":"International","genre_handle":"International","genre_color":"#CC3300"}]}
     */
    try {
        String genreJson = IOUtils.toString(new URL(url));
        JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
        // get the title
        System.out.println(genreJsonObject.get("title"));
        // get the data
        JSONArray genreArray = (JSONArray) genreJsonObject.get("dataset");
        // get the first genre
        JSONObject firstGenre = (JSONObject) genreArray.get(0);
        System.out.println(firstGenre.get("genre_title"));
    } catch (IOException | ParseException e) {
        e.printStackTrace();
    }
}

From source file:Controller.MainClass.java

public static String getLocationFromAPi(String CityName) throws ParseException {
    String[] list;/*from   www  .ja va 2s . c o  m*/
    list = CityName.replaceAll("[^a-zA-Z]", "").toLowerCase().split("\\s+");
    CityName = list[0];
    String Address = "";
    String url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + CityName + "&sensor=false";

    try {
        String genreJson = IOUtils.toString(new URL(url));
        JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
        JSONArray genreArray = (JSONArray) genreJsonObject.get("results");
        if (genreArray.size() == 0) {
            return "";
        } else {
            JSONObject firstGenre = (JSONObject) genreArray.get(0);
            String City = firstGenre.get("formatted_address").toString();
            JSONObject obj = (JSONObject) firstGenre.get("geometry");
            JSONObject loc = (JSONObject) obj.get("location");
            String lat = loc.get("lat").toString();
            String lng = loc.get("lng").toString();
            Address = (String) (lat + "/" + lng + "/" + City);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return Address;
}

From source file:net.paissad.minus.utils.JSONUtils.java

/**
 * Parse a String (usually an HTTP response which is a JSON formatted
 * String) and returns its <tt>Map</tt> view.
 * //from  w  w w .  jav  a 2s . c o m
 * @param response - A formatted JSON <tt>String</tt>.
 * @return A {@link Map} representing the JSON response.
 * @throws ParseException
 * @throws MinusException If the specified <tt>String</tt> cannot be parsed
 *             as a <tt>Map</tt> or is not a <tt>JSONObject</tt>.
 */
public static Map<String, Object> getMapFromJSONString(final String response)
        throws ParseException, MinusException {

    Object obj = JSONValue.parseWithException(response);
    if (obj instanceof JSONObject) {
        @SuppressWarnings("unchecked")
        Map<String, Object> jsonResult = ((HashMap<String, Object>) obj);
        return jsonResult;
    } else {
        throw new MinusException("The JSON string is not of type JSONObject => " + response);
    }
}

From source file:com.juniform.JUniformPackerJSON.java

@Override
public JUniformObject toUniformObjectFromStream(InputStream stream) {
    try (InputStreamReader inputStreamReader = new InputStreamReader(stream)) {
        Object value = JSONValue.parseWithException(inputStreamReader);
        return this.toUniformObjectFromObject(value);
    } catch (IOException | ParseException ex) {
        return JUniformObject.OBJECT_NIL;
    }/*from w ww.  j a v  a 2s  .c  om*/
}

From source file:com.anto89.processor.ProcessorManager.java

public boolean run(String urlString) {

    JSONArray json = null;//from  www  . j a v  a  2 s.c om
    try {
        URL url = new URL(urlString);
        String jsonResult = IOUtils.toString(url);
        json = (JSONArray) JSONValue.parseWithException(jsonResult);

    } catch (MalformedURLException ex) {
        Logger.getLogger(ProcessorManager.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (IOException | ParseException ex) {
        Logger.getLogger(ProcessorManager.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }

    // data valid only
    if (json == null || json.isEmpty()) {
        return false;
    }

    // setup result
    result.put("url_data", urlString);
    result.put("process_time", new Date());
    for (Processor p : list) {
        p.setReturnJson(result);
    }

    // main processing
    for (int i = 0; i < json.size(); i++) {
        JSONObject data = (JSONObject) json.get(i);
        for (Processor p : list) {
            p.run(data);
        }
    }

    // return result
    for (Processor p : list) {
        p.getReturnJson();
    }
    return true;
}

From source file:name.martingeisse.common.javascript.analyze.JsonAnalyzer.java

/**
 * Parses a JSON-encoded string and analyzes the result.
 * @param json the JSON-encoded string/*w ww .  ja  v a 2 s . com*/
 * @return the analyzer
 */
public static JsonAnalyzer parse(final String json) {
    try {
        return new JsonAnalyzer(JSONValue.parseWithException(json));
    } catch (ParseException e) {
        throw new JsonAnalysisException("Parse exception in JSON input: " + json);
    }
}

From source file:com.flaptor.indextank.api.resources.DeleteDocs.java

/**
 * @see java.lang.Runnable#run()//from   w  ww.j a v  a  2 s.  c om
 */
public void run() {
    IndexEngineApi api = (IndexEngineApi) ctx().getAttribute("api");
    try {
        Object parse = JSONValue.parseWithException(req().getReader());
        if (parse instanceof JSONObject) { // 200, 400, 404, 409, 503
            JSONObject jo = (JSONObject) parse;
            try {
                deleteDocument(api, jo);
                res().setStatus(200);
                return;

            } catch (Exception e) {
                e.printStackTrace();
                if (LOG_ENABLED)
                    LOG.severe(e.getMessage());
                res().setStatus(400);
                print("Invalid or missing argument"); // TODO: descriptive error msg
                return;
            }
        } else if (parse instanceof JSONArray) {
            JSONArray statuses = new JSONArray();
            JSONArray ja = (JSONArray) parse;
            if (!validateDocuments(ja)) {
                res().setStatus(400);
                print("Invalid or missing argument"); // TODO: descriptive error msg
                return;
            }
            boolean hasError = false;
            for (Object o : ja) {
                JSONObject jo = (JSONObject) o;
                JSONObject status = new JSONObject();
                try {
                    deleteDocument(api, jo);
                    status.put("added", true);
                } catch (Exception e) {
                    status.put("added", false);
                    status.put("error", "Invalid or missing argument"); // TODO: descriptive error msg
                    hasError = true;
                }
                statuses.add(status);
            }
            print(statuses.toJSONString());
            return;
        }
    } catch (IOException e) {
        if (LOG_ENABLED)
            LOG.severe("DELETE doc, parse input " + e.getMessage());
    } catch (ParseException e) {
        if (LOG_ENABLED)
            LOG.severe("DELETE doc, parse input " + e.getMessage());
    } catch (Exception e) {
        if (LOG_ENABLED)
            LOG.severe("DELETE doc " + e.getMessage());
    }
    res().setStatus(503);
    print("Service unavailable"); // TODO: descriptive error msg
}

From source file:com.healthcit.analytics.utils.ExcelExportUtils.java

public static JSONObject getAsJsonObject(String jsonString) {
    JSONObject obj = null;//from   w  ww  .ja  v  a  2s .  c o m

    try {
        obj = (JSONObject) JSONValue.parseWithException(jsonString);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return obj;
}

From source file:com.juniform.JUniformPackerJSON.java

@Override
public JUniformObject toUniformObjectFromString(String string) {
    try {//from   ww w . j  a  v a2  s . c o m
        Object value = JSONValue.parseWithException(string);
        return this.toUniformObjectFromObject(value);
    } catch (ParseException ex) {
        return JUniformObject.OBJECT_NIL;
    }
}

From source file:Basics.JsonCityReader.java

private void jsonBreakDown(String foo, int i) {

    try {/*from w  ww .  j a va  2 s .com*/

        String jString = IOUtils.toString(new URL(foo));
        JSONObject jObject = (JSONObject) JSONValue.parseWithException(jString);

        JSONArray stations = (JSONArray) jObject.get("stations");
        Iterator it = stations.iterator();
        jObject = (JSONObject) it.next();

        //Getting city information.
        String tempID = (String) jObject.get("id");
        String tempScore = (String) jObject.get("score");
        String tempDistance = (String) jObject.get("distance");
        String Coordinates = jObject.get("coordinate").toString();

        //Getting Coordinates.
        JSONObject coordinate = (JSONObject) JSONValue.parseWithException(Coordinates);
        String tempType = (String) coordinate.get("type");
        Double tempX = (Double) coordinate.get("x");
        Double tempY = (Double) coordinate.get("y");

        //Creating temporary city with the information.
        Coordinates tempCoordinates = new Coordinates(tempType, tempX, tempY);
        Cities tempCity = new Cities(tempID, cities.get(i), tempScore, tempCoordinates, tempDistance);

        //Adding city to the list.
        tempCity.addCity(tempCity);

        //Catching errors and retrying.
    } catch (IOException | ParseException e) {
        if (counter == 0) {
            flag = false;
            System.out.println(
                    "An error occurred while trying to get " + cities.get(i) + "'s information. \nRetrying...");
        }
        if (counter < 5) {
            counter++;
            jsonBreakDown(foo, i);
            //If retrying fails more than four times, the application stops.
        } else {
            System.out.println("There was an issue with retrieving " + cities.get(i)
                    + "'s data.\nPlease restart the application and try again.");
            System.exit(1);
        }
    }
    if (!flag) {
        System.out.println("The error has been resolved. Continuing to the next city.");
        counter = 0;
        flag = true;
    }

}