Example usage for org.json.simple JSONValue parse

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

Introduction

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

Prototype

public static Object parse(String s) 

Source Link

Usage

From source file:net.jakobnielsen.imagga.crop_slice.convert.SmartCroppingConverter.java

@Override
public List<SmartCropping> convert(String jsonString) {
    if (jsonString == null) {
        throw new ConverterException("The given JSON string is null");
    }//from w ww.  j  av a 2s.com

    JSONObject json = (JSONObject) JSONValue.parse(jsonString);
    if (!json.containsKey(SMART_CROPPINGS)) {
        throw new ConverterException(SMART_CROPPINGS + " key missing from json : " + jsonString);
    }
    JSONArray jsonArray = (JSONArray) json.get(SMART_CROPPINGS);

    List<SmartCropping> smartCroppings = new ArrayList<SmartCropping>();

    for (Object aJsonArray : jsonArray) {

        JSONObject smartCroppingObject = (JSONObject) aJsonArray;

        String url = getString("url", smartCroppingObject);

        List<Cropping> croppings = new ArrayList<Cropping>();

        if (smartCroppingObject.containsKey(CROPPINGS)) {

            JSONArray croppingsArray = (JSONArray) smartCroppingObject.get(CROPPINGS);

            for (Object aCroppingsArray : croppingsArray) {

                JSONObject croppingObject = (JSONObject) aCroppingsArray;

                croppings.add(new Cropping(
                        new Resolution(getInteger("target_width", croppingObject),
                                getInteger("target_height", croppingObject)),
                        new Region(getInteger("x1", croppingObject), getInteger("y1", croppingObject),
                                getInteger("x2", croppingObject), getInteger("y2", croppingObject))));
            }
            smartCroppings.add(new SmartCropping(url, croppings));
        }
    }

    return smartCroppings;
}

From source file:net.jakobnielsen.imagga.color.convert.ColorsConverter.java

@Override
public List<ColorResult> convert(String jsonString) {
    if (jsonString == null) {
        throw new ConverterException("The given JSON string is null");
    }//from w w w  .  j ava2  s  .  co  m

    JSONObject json = (JSONObject) JSONValue.parse(jsonString);

    if (!json.containsKey(COLORS)) {
        throw new ConverterException(COLORS + " key missing from json : " + jsonString);
    }

    JSONArray jsonArray = (JSONArray) json.get(COLORS);
    List<ColorResult> colorResults = new ArrayList<ColorResult>();

    for (Object co : jsonArray) {

        JSONObject colorResultJSON = (JSONObject) co;
        String url = getString("url", colorResultJSON);
        JSONObject infoJSON = (JSONObject) colorResultJSON.get("info");
        List<ExtendedColor> imageColors = new ArrayList<ExtendedColor>();
        List<ExtendedColor> foregroundColors = new ArrayList<ExtendedColor>();
        List<ExtendedColor> backgroundColors = new ArrayList<ExtendedColor>();
        Double objectPercentage = null;
        Long colorVariance = null;

        addColors("image_colors", infoJSON, imageColors);
        addColors("foreground_colors", infoJSON, foregroundColors);
        addColors("background_colors", infoJSON, backgroundColors);

        if (infoJSON.containsKey(OBJECT_PERCENTAGE)) {
            objectPercentage = getDouble(OBJECT_PERCENTAGE, infoJSON);
        }

        if (infoJSON.containsKey("color_variance")) {
            colorVariance = getLong("color_variance", infoJSON);
        }

        colorResults.add(new ColorResult(url,
                new Info(imageColors, foregroundColors, backgroundColors, objectPercentage, colorVariance)));
    }

    return colorResults;
}

From source file:com.bowprog.sql.constructeur.CreateDataBase.java

private void fileRead(File file) {
    try {//from  w  w  w.  java2 s . c o  m
        Table table = new Table(statement);
        JSONObject obj = (JSONObject) JSONValue.parse(new FileReader(file));

        table.appliqueJSON(obj);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(CreateDataBase.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:Models.Taxonomy.Repository.RepositoryTNRS.java

/**
 * Method that consuming web services from tnrs and get results
 * @param name Name from specie to evaluate
 * @param best True for best results, false if all results
 * @return //  ww w .  j a  v  a 2 s  .  c o m
 */
public static TNRS[] get(String name, boolean best) {
    TNRS[] a = null;
    try {
        if (db == null)
            db = new HashMap();
        if (db.containsKey(name.trim().replaceAll(" ", "_")))
            return (TNRS[]) db.get(name.trim().replaceAll(" ", "_"));
        URL url = new URL(Configuration.getParameter("tnrs_url_base")
                + (best ? "retrieve=best" : "retrieve=all") + "&names=" + name.replaceAll(" ", "%20"));
        BufferedReader lector = new BufferedReader(new InputStreamReader(url.openStream()));
        String textJson = lector.readLine();
        if (textJson == null)
            throw new Exception("Don't found item " + name);
        JSONArray jsNames = (JSONArray) ((JSONObject) JSONValue.parse(textJson)).get("items");
        a = new TNRS[jsNames.size()];
        for (int i = 0; i < a.length; i++)
            a[i] = new TNRS((JSONObject) jsNames.get(i));
        db.put(name.trim().replaceAll(" ", "_"), a);
    } catch (Exception ex) {
        a = null;
        System.out.println("Error TNRS: " + ex);
    }
    return a;
}

From source file:logic.ZybezItemListing.java

private void setItemOffers() {

    JSONObject o = (JSONObject) JSONValue.parse(listingJsonString);
    String offerString = o.get("offers").toString();
    JSONArray array = (JSONArray) JSONValue.parse(offerString);

    numOffers = array.size();/*w w w . j a  v a 2s  .co m*/
    for (int i = 0; i < numOffers; i++) {
        JSONObject o2 = (JSONObject) JSONValue.parse(array.get(i).toString());

        ZybezOffer z = new ZybezOffer(itemID, o2.get("selling").toString(), o2.get("quantity").toString(),
                o2.get("price").toString(), itemName, o2.get("rs_name").toString(), o2.get("notes").toString());

        offerList.add(z);
    }

}

From source file:ch.simas.jtoggl.TimeEntry.java

public TimeEntry(String jsonString) {
    JSONObject object = (JSONObject) JSONValue.parse(jsonString);
    this.id = (Long) object.get("id");
    this.description = (String) object.get("description");
    this.start = DateUtil.convertStringToDate((String) object.get("start"));
    this.stop = DateUtil.convertStringToDate((String) object.get("stop"));
    this.duration = (Long) object.get("duration");
    this.billable = (Boolean) object.get("billable");
    this.duronly = (Boolean) object.get("duronly");
    created_with = (String) object.get("created_with");
    this.pid = (Long) object.get("pid");
    this.wid = (Long) object.get("wid");
    this.tid = (Long) object.get("tid");

    JSONObject workspaceObject = (JSONObject) object.get("workspace");
    if (workspaceObject != null) {
        this.workspace = new Workspace(workspaceObject.toJSONString());
    }/*from   www .  j av a  2  s.  co  m*/

    JSONObject projectObject = (JSONObject) object.get("project");
    if (projectObject != null) {
        this.project = new Project(projectObject.toJSONString());
    }
    // Tag names
    JSONArray tagsArray = (JSONArray) object.get("tags");
    List<String> tags = new ArrayList<String>();
    if (tagsArray != null) {
        for (Object arrayObject : tagsArray) {
            tags.add((String) arrayObject);
        }
    }
    this.tag_names = tags;
}

From source file:io.mingle.v1.Connection.java

public Response run(String comprehension) {
    String expr = "{ \"query\": \"" + comprehension + "\", \"limit\": 10000 }";
    try {/*from   w ww .jav a  2  s.com*/
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.connect();

        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        out.write(expr, 0, expr.length());
        out.flush();
        out.close();

        InputStream in = conn.getInputStream();
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        byte[] chunk = new byte[4096];
        int read = 0;
        while ((read = in.read(chunk)) > 0) {
            buf.write(chunk, 0, read);
        }
        in.close();

        String str = buf.toString();
        System.out.println("GOT JSON: " + str);
        return new Response(JSONValue.parse(str));
    } catch (Exception e) {
        System.err.printf("failed to execute: %s\n", expr);
        e.printStackTrace();
    }

    return null;
}

From source file:mml.handler.get.MMLGetVersion1Handler.java

public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws MMLException {
    try {/*from   w ww  .j  a va 2  s.  co  m*/
        Connection conn = Connector.getConnection();
        docid = request.getParameter(Params.DOCID);
        String res = conn.getFromDb(Database.CORTEX, docid);
        if (res != null) {
            JSONObject jObj = (JSONObject) JSONValue.parse(res);
            if (jObj.containsKey(JSONKeys.VERSION1)) {
                version1 = (String) jObj.get(JSONKeys.VERSION1);
                if (!Layers.isNewStyleLayer(version1)) {
                    if (((String) jObj.get(JSONKeys.FORMAT)).startsWith("MVD")) {
                        String body = (String) jObj.get(JSONKeys.BODY);
                        if (body != null) {
                            MVD mvd = MVDFile.internalise(body);
                            String[] all = getAllVersions(mvd);
                            version1 = Layers.upgradeLayerName(all, version1);
                        }
                    } else {
                        String[] all = new String[1];
                        all[0] = version1;
                        version1 = Layers.upgradeLayerName(all, version1);
                    }
                }
            } else if (((String) jObj.get(JSONKeys.FORMAT)).startsWith("MVD")) {
                String body = (String) jObj.get(JSONKeys.BODY);
                if (body != null) {
                    MVD mvd = MVDFile.internalise(body);
                    String[] all = getAllVersions(mvd);
                    String groupPath = mvd.getGroupPath((short) 1);
                    String shortName = mvd.getVersionShortName((short) 1);
                    version1 = Layers.upgradeLayerName(all, groupPath + "/" + shortName);
                    jObj.put(JSONKeys.VERSION1, version1);
                    jObj.remove(JSONKeys._ID);
                    conn.putToDb(Database.CORTEX, docid, jObj.toJSONString());
                } else
                    version1 = ""; // nothing there
            } else
                version1 = "/base";
        } else
            version1 = "";
        response.setContentType("text/plain");
        response.getWriter().write(version1.replaceAll("\\\\/", "/"));
    } catch (Exception e) {
        throw new MMLException(e);
    }
}

From source file:com.turt2live.hurtle.uuid.UUIDServiceProvider.java

/**
 * Gets the name of a player for the specified UUID.
 *
 * @param uuid the uuid to lookup, cannot be null
 *
 * @return the player's name, or null if not found or for invalid input
 *///from   ww w  . ja  v a 2s . c o  m
public static String getName(UUID uuid) {
    if (uuid == null)
        return null;
    try {
        URL url = new URL("http://uuid.turt2live.com/name/" + uuid.toString().replaceAll("-", ""));
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        String parsed = "";
        String line;
        while ((line = reader.readLine()) != null)
            parsed += line;
        reader.close();

        Object o = JSONValue.parse(parsed);
        if (o instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) o;
            Object status = jsonObject.get("status");
            if (status instanceof String && ((String) status).equalsIgnoreCase("ok")) {
                o = jsonObject.get("name");
                if (o instanceof String) {
                    return (String) o;
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:me.neatmonster.spacertk.plugins.PluginsRequester.java

@Override
@SuppressWarnings("unchecked")
public void run() {
    try {/*from   ww w.  j a v  a 2  s  .c  o  m*/
        final URLConnection connection = new URL("http://api.bukget.org/api2/bukkit/plugins").openConnection();
        final BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(connection.getInputStream()));
        final StringBuffer stringBuffer = new StringBuffer();
        String line;
        while ((line = bufferedReader.readLine()) != null)
            stringBuffer.append(line);
        bufferedReader.close();
        List<JSONObject> apiResponse = (JSONArray) JSONValue.parse(stringBuffer.toString());

        for (JSONObject o : apiResponse)
            PluginsManager.pluginsNames.add((String) o.get("name"));

    } catch (Exception e) {
        System.out.println("[SpaceBukkit] Unable to connect to BukGet, BukGet features will be disabled");
    }
}