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

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

Introduction

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

Prototype

public Object parse(Reader in) throws IOException, ParseException 

Source Link

Usage

From source file:com.sugarcrm.candybean.configuration.Configuration.java

public static String getPlatformValue(Properties props, String key) {
    String platform = Utils.getCurrentPlatform();
    String valueStr = props.getProperty(key);
    JSONParser parser = new JSONParser();
    try {/*from ww w  . j  av a2  s .  com*/
        Object valueObject = parser.parse(valueStr);
        if (valueObject instanceof Map) {
            JSONObject valueMap = (JSONObject) valueObject;
            return (String) valueMap.get(platform);
        } else {
            return valueStr;
        }
    } catch (ParseException pe) {
        return valueStr;
    }
}

From source file:model.Post_store.java

public static String getposttitle(int id) {

    JSONParser parser = new JSONParser();
    String title = "";

    try {//from  ww w  . j  av  a2s  .  c o m

        Object obj = parser.parse(new FileReader(root + "posts/" + id + ".json"));

        JSONObject jsonObject = (JSONObject) obj;

        title = (String) jsonObject.get("title");
        //System.out.println(title);

    } catch (FileNotFoundException e) {
        System.out.println(e);
    } catch (IOException e) {
        System.out.println(e);
    } catch (ParseException e) {
        System.out.println(e);
    }

    return title;

}

From source file:model.Post_store.java

public static String getpostcontent(int id) {

    JSONParser parser = new JSONParser();
    String content = "";

    try {//from   w w w .  ja  v a2s.  c  o  m

        Object obj = parser.parse(new FileReader(root + "posts/" + id + ".json"));

        JSONObject jsonObject = (JSONObject) obj;

        content = (String) jsonObject.get("content");
        //System.out.println(content);

    } catch (FileNotFoundException e) {
        System.out.println(e);
    } catch (IOException e) {
        System.out.println(e);
    } catch (ParseException e) {
        System.out.println(e);
    }

    return content;

}

From source file:model.Post_store.java

public static int getlastid() {
    JSONParser parser = new JSONParser();
    int lastid = 1;
    try {/*  w  w w .ja  v a  2  s .c  o m*/

        Object idObj = parser.parse(new FileReader(root + "posts/lastid.json"));

        JSONObject jsonObject = (JSONObject) idObj;

        String slastid = jsonObject.get("lastid").toString();
        lastid = Integer.parseInt(slastid);

        //System.out.println(lastid);

    } catch (FileNotFoundException e) {
        JSONObject newIdObj = new JSONObject();
        lastid = 1;
        newIdObj.put("lastid", lastid);

        try (FileWriter file = new FileWriter(root + "posts/lastid.json");) {
            file.write(newIdObj.toJSONString());
            file.flush();
            file.close();

        } catch (IOException ex) {
            System.out.println(e);
        }
    } catch (IOException e) {
        System.out.println(e);
    } catch (ParseException e) {
        System.out.println(e);
    }

    return lastid;
}

From source file:com.avinashbehera.sabera.network.HttpClient.java

public static JSONObject SendHttpPostUsingHttpClient(String URL, JSONObject jsonObjSend) {

    try {//from   w ww.j ava  2 s.c  o  m
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 60 * 1000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        int timeoutSocket = 60 * 1000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        //httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");
        //httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression

        long t = System.currentTimeMillis();
        Log.d(TAG, "httpPostReuest = " + httpPostRequest.toString());
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]");

        // Get hold of the response entity (-> the data):
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // Read the content stream
            InputStream instream = entity.getContent();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                instream = new GZIPInputStream(instream);
            }

            // convert content stream to a String
            String resultString = convertStreamToString(instream);
            instream.close();
            resultString = resultString.substring(1, resultString.length() - 1); // remove wrapping "[" and "]"

            // Transform the String into a JSONObject
            JSONParser parser = new JSONParser();
            JSONObject jsonObjRecv = (JSONObject) parser.parse(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");

            return jsonObjRecv;
        }

    } catch (Exception e) {
        Log.d(TAG, "catch block");
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    }
    Log.d(TAG, "SendHttpPostUsingHttpClient returning null");
    return null;
}

From source file:halive.shootinoutside.common.core.game.map.GameMap.java

public static GameMap loadGameMapFromJSONString(String s) throws ParseException {
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(s);
    if (obj instanceof JSONObject) {
        JSONObject in = (JSONObject) obj;
        GameMap map = new GameMap();
        //Verify Validity
        if (!in.get("type").equals("soTileMap"))
            return null;
        //TODO Implement Determination of the Deserializer depending on the version
        //Load Width/Height and Mapname
        map.mapName = in.get("mapName").toString();
        map.width = (int) (long) in.get("width");
        map.height = (int) (long) in.get("height");
        //Load the Map Data
        byte[] mapData = Base64.getDecoder().decode((String) in.get("mapDataB64"));
        map.loadTilesFromByteArray(mapData);
        //Load the Spawnpositions
        int amtTeams = (int) (long) in.get("amtTeams");
        if (amtTeams != Teams.values().length) {
            return null;
        }// w w  w .j a  va  2s . c o m
        for (int i = 0; i < amtTeams; i++) {
            JSONObject o = (JSONObject) in.get("spawn_team_" + i);
            int len = (int) (long) o.get("length");
            for (int j = 0; j < len; j++) {
                JSONObject oj = (JSONObject) o.get("" + j);
                map.spawnPositions[i].add(Vector2D.fromJSONObject(oj));
            }
        }
        //Load the ItemLayer
        map.itemLayer = ItemLayer.fromJSONObject((JSONObject) in.get("itemLayer"));
        //Read the Image
        map.textureSheet = Base64.getDecoder().decode(in.get("tileImageB64").toString());
        return map;
    } else {
        return null;
    }
}

From source file:cpd3314.buildit12.CPD3314BuildIt12.java

/**
 * Build a sample method that saves a handful of car instances as Serialized
 * objects, and as JSON objects, then re-open the saved versions in a
 * different method/*from  w  w  w  .ja v a  2 s.  c o m*/
 */
public static void doBuildIt2Input() {
    // Unserialize the Objects -- Save them to an ArrayList and Output
    try {
        FileInputStream objFile = new FileInputStream("cars.obj");
        ObjectInputStream objStream = new ObjectInputStream(objFile);

        ArrayList<Car> cars = new ArrayList<>();

        boolean eof = false;
        while (!eof) {
            try {
                cars.add((Car) objStream.readObject());
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(CPD3314BuildIt12.class.getName()).log(Level.SEVERE, null, ex);
            } catch (EOFException ex) {
                // We must catch the EOF exception to leave the loop
                eof = true;
            }
        }

        System.out.println("Unserialized Data:");
        for (Car car : cars) {
            System.out.printf("Make: %s, Model: %s, Year: %d\n", car.getMake(), car.getModel(), car.getYear());
        }
    } catch (IOException ex) {
        Logger.getLogger(CPD3314BuildIt12.class.getName()).log(Level.SEVERE, null, ex);
    }

    // Read from JSON and Output
    try {
        File file = new File("cars.json");
        Scanner input = new Scanner(file);
        while (input.hasNext()) {
            JSONParser parse = new JSONParser();
            try {
                // This should be the root JSON Object, which has an array of Car objects
                JSONObject json = (JSONObject) parse.parse(input.nextLine());

                // We pull the array out to work with it
                JSONArray cars = (JSONArray) json.get("cars");

                System.out.println("Un-JSON-ed Data:");
                for (Object car : cars) {
                    // Convert each Object to a JSONObject
                    JSONObject carJSON = (JSONObject) car;
                    // Convert each JSONObject to an actual Car
                    Car carObj = new Car(carJSON);
                    // Output from the Actual Car class                        
                    System.out.printf("Make: %s, Model: %s, Year: %d\n", carObj.getMake(), carObj.getModel(),
                            carObj.getYear());
                }
            } catch (ParseException ex) {
                Logger.getLogger(CPD3314BuildIt12.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(CPD3314BuildIt12.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:gessi.ossecos.graph.GraphModel.java

public static void IStarJsonToGraphFile(String iStarModel, String layout, String typeGraph)
        throws ParseException {
    JSONParser parser = new JSONParser();
    JSONObject jsonObject = (JSONObject) parser.parse(iStarModel);

    JSONArray jsonArrayNodes = (JSONArray) jsonObject.get("nodes");
    JSONArray jsonArrayEdges = (JSONArray) jsonObject.get("edges");
    String modelType = jsonObject.get("modelType").toString();

    // System.out.println(modelType);
    // System.out.println(jsonArrayNodes.toJSONString());
    // System.out.println(jsonArrayEdges.toJSONString());

    System.out.println(jsonObject.toJSONString());

    Hashtable<String, String> nodesHash = new Hashtable<String, String>();
    Hashtable<String, String> boundaryHash = new Hashtable<String, String>();
    Hashtable<String, Integer> countNodes = new Hashtable<String, Integer>();
    ArrayList<String> boundaryItems = new ArrayList<String>();
    ArrayList<String> actorItems = new ArrayList<String>();
    GraphViz gv = new GraphViz();
    gv.addln(gv.start_graph());//from  ww w . j a  v a  2s.  c  o m

    String nodeType;
    String nodeName;
    String nodeBoundary;
    for (int i = 0; i < jsonArrayNodes.size(); i++) {

        jsonObject = (JSONObject) jsonArrayNodes.get(i);
        nodeName = jsonObject.get("name").toString().replace(" ", "_");
        // .replace("(", "").replace(")", "");
        nodeName = nodeName.replaceAll("[\\W]|`[_]", "");
        nodeType = jsonObject.get("elemenType").toString();
        nodeBoundary = jsonObject.get("boundary").toString();
        // TODO: Verify type of diagram
        // if (!nodeType.equals("actor") & !nodeBoundary.equals("boundary"))
        // {
        if (countNodes.get(nodeName) == null) {
            countNodes.put(nodeName, 0);
        } else {
            countNodes.put(nodeName, countNodes.get(nodeName) + 1);
            nodeName += "_" + countNodes.put(nodeName, 0);

        }
        gv.addln(renderNode(nodeName, nodeType));

        // }

        nodesHash.put(jsonObject.get("id").toString(), nodeName);
        boundaryHash.put(jsonObject.get("id").toString(), nodeBoundary);
        if (nodeType.equals("actor")) {
            actorItems.add(nodeName);
        }
    }

    String edgeType = "";
    String source = "";
    String target = "";
    String edgeSubType = "";
    int subgraphCount = 0;
    boolean hasCluster = false;
    nodeBoundary = "na";
    String idSource;
    String idTarget;
    for (int i = 0; i < jsonArrayEdges.size(); i++) {

        jsonObject = (JSONObject) jsonArrayEdges.get(i);
        edgeSubType = jsonObject.get("linksubtype").toString();
        edgeType = renderEdge(edgeSubType, jsonObject.get("linktype").toString());
        idSource = jsonObject.get("source").toString();
        idTarget = jsonObject.get("target").toString();
        source = nodesHash.get(idSource);
        target = nodesHash.get(idTarget);

        if (!boundaryHash.get(idSource).toString().equals("boundary")
                && !boundaryHash.get(idTarget).toString().equals("boundary")) {
            if (!boundaryHash.get(idSource).toString().equals(nodeBoundary)) {
                nodeBoundary = boundaryHash.get(idSource).toString();
                if (hasCluster) {
                    gv.addln(gv.end_subgraph());
                    hasCluster = false;

                } else {
                    hasCluster = true;
                }
                gv.addln(gv.start_subgraph(subgraphCount));
                gv.addln(actorItems.get(subgraphCount++));
                gv.addln("style=filled;");
                gv.addln("color=lightgrey;");

            }
            gv.addln(source + "->" + target + edgeType);

        } else {

            boundaryItems.add(source + "->" + target + edgeType);

        }

    }
    if (subgraphCount > 0) {
        gv.addln(gv.end_subgraph());
    }
    for (String boundaryE : boundaryItems) {
        gv.addln(boundaryE);
    }
    gv.addln(gv.end_graph());

    String type = typeGraph;
    // String type = "dot";
    // String type = "fig"; // open with xfig
    // String type = "pdf";
    // String type = "ps";
    // String type = "svg"; // open with inkscape
    // String type = "png";
    // String type = "plain";

    String repesentationType = layout;
    // String repesentationType= "neato";
    // String repesentationType= "fdp";
    // String repesentationType= "sfdp";
    // String repesentationType= "twopi";
    // String repesentationType= "circo";

    // //File out = new File("/tmp/out"+gv.getImageDpi()+"."+ type); //
    // Linux
    File out = new File("Examples/out." + type); // Windows
    gv.writeGraphToFile(gv.getGraph(gv.getDotSource(), type, repesentationType), out);

}

From source file:com.avinashbehera.sabera.network.HttpClient.java

public static JSONObject SendHttpPostUsingUrlConnection(String url, JSONObject jsonObjSend) {

    URL sendUrl;//  w w w.ja  va2  s .co m
    try {
        sendUrl = new URL(url);
    } catch (MalformedURLException e) {
        Log.d(TAG, "SendHttpPostUsingUrlConnection malformed URL");
        return null;
    }

    HttpURLConnection conn = null;

    try {
        conn = (HttpURLConnection) sendUrl.openConnection();
        conn.setReadTimeout(15000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setChunkedStreamingMode(1024);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.addRequestProperty("Content-length", jsonObjSend.toJSONString().length() + "");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        //writer.write(getPostDataStringfromJsonObject(jsonObjSend));
        Log.d(TAG, "jsonobjectSend = " + jsonObjSend.toString());
        //writer.write(jsonObjSend.toString());
        writer.write(String.valueOf(jsonObjSend));

        writer.flush();
        writer.close();
        os.close();

        int responseCode = conn.getResponseCode();
        Log.d(TAG, "responseCode = " + responseCode);

        if (responseCode == HttpsURLConnection.HTTP_OK) {

            Log.d(TAG, "responseCode = HTTP OK");

            InputStream instream = conn.getInputStream();

            String resultString = convertStreamToString(instream);
            instream.close();
            Log.d(TAG, "resultString = " + resultString);
            //resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"

            // Transform the String into a JSONObject
            JSONParser parser = new JSONParser();
            JSONObject jsonObjRecv = (JSONObject) parser.parse(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");

            return jsonObjRecv;

        }

    } catch (Exception e) {
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return null;

}

From source file:com.apigee.edge.config.mavenplugin.APIProductMojo.java

public static List getAPIProduct(ServerProfile profile) throws IOException {

    HttpResponse response = RestUtil.getOrgConfig(profile, "apiproducts");
    if (response == null)
        return new ArrayList();
    JSONArray products = null;//from  w ww  .j  av a2 s .com
    try {
        logger.debug("output " + response.getContentType());
        // response can be read only once
        String payload = response.parseAsString();
        logger.debug(payload);

        /* Parsers fail to parse a string array.
         * converting it to an JSON object as a workaround */
        String obj = "{ \"products\": " + payload + "}";

        JSONParser parser = new JSONParser();
        JSONObject obj1 = (JSONObject) parser.parse(obj);
        products = (JSONArray) obj1.get("products");

    } catch (ParseException pe) {
        logger.error("Get API Product parse error " + pe.getMessage());
        throw new IOException(pe.getMessage());
    } catch (HttpResponseException e) {
        logger.error("Get API Product error " + e.getMessage());
        throw new IOException(e.getMessage());
    }

    return products;
}