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:com.noelportugal.amazonecho.WitAi.java

public String getStatus(String text) {
    String ret = "off";
    try {/*w  w w .  ja v a2 s. c  o  m*/

        String json = getJson(text);

        Object obj = JSONValue.parse(json);
        JSONObject jsonObject = (JSONObject) obj;
        JSONArray values = (JSONArray) jsonObject.get("outcomes");
        JSONObject outcome = (JSONObject) values.get(0);

        JSONObject on_off = (JSONObject) outcome.get("entities");
        JSONArray on_off_values = (JSONArray) on_off.get("on_off");
        JSONObject value = (JSONObject) on_off_values.get(0);
        ret = value.get("value").toString();

    } catch (Exception e) {
        ret = "off";
    }

    return ret.toLowerCase();
}

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

/**
* Handle the request//from ww w  . j  a  v  a  2s  .c  om
* @param request the request
* @param response the response
* @param urn the remaining urn of the request
* @throws MMLException 
*/
public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws MMLException {
    try {
        String jBody = null;
        docid = request.getParameter(JSONKeys.DOCID);
        if (docid != null) {
            Connection conn = Connector.getConnection();
            String jStr = conn.getFromDb(Database.CORTEX, docid);
            JSONObject jObj = (JSONObject) JSONValue.parse(jStr);
            String style = (String) jObj.get(JSONKeys.STYLE);
            jStr = conn.getFromDb(Database.CORFORM, style);
            if (jStr == null)
                jBody = getDefaultResource(docid);
            else {
                jObj = (JSONObject) JSONValue.parse(jStr);
                jBody = (String) jObj.get(JSONKeys.BODY);
            }
        } else
            jBody = getDefaultResource("default");
        setEncoding(request);
        response.setContentType("text/plain");
        response.setCharacterEncoding(encoding);
        response.getWriter().println(jBody);
    } catch (Exception e) {
        throw new MMLException(e);
    }
}

From source file:bolt.DucksBoard.java

public DucksBoard(String json) {
    Object obj = JSONValue.parse(json);
    JSONArray array = (JSONArray) obj;//from w  w  w  .j ava2 s  .c  o m
    JSONObject obj2 = (JSONObject) array.get(0);
    this.idString = obj2.get("id").toString();
    this.keyString = obj2.get("key").toString();

}

From source file:de.cgarbs.lib.json.type.JSONTypeFactoryTest.java

@Test
public void checkUnwrapJSONObject_Exception() {
    try {//from ww w  .  j a v a 2s. com
        JSONTypeFactory.unwrapJSONObject("foo");
        fail("no exception thrown");
    } catch (JSONException e) {
        checkJSONException(e, ERROR.JSON_TO_JAVA, "root element");
    }

    try {
        JSONTypeFactory.unwrapJSONObject(JSONValue.parse("{\"version\":\"1\",\"attributes\":{}}"));
        fail("no exception thrown");
    } catch (JSONException e) {
        checkJSONException(e, ERROR.JSON_TO_JAVA, "class [");
    }

    try {
        JSONTypeFactory.unwrapJSONObject(JSONValue.parse("{\"class\":\"JSONColor\",\"attributes\":{}}"));
        fail("no exception thrown");
    } catch (JSONException e) {
        checkJSONException(e, ERROR.JSON_TO_JAVA, "version [");
    }

    try {
        JSONTypeFactory.unwrapJSONObject(JSONValue.parse("{\"class\":\"JSONColor\",\"version\":\"1\"}"));
        fail("no exception thrown");
    } catch (JSONException e) {
        checkJSONException(e, ERROR.JSON_TO_JAVA, "attributes [");
    }

    try {
        JSONTypeFactory.unwrapJSONObject(
                JSONValue.parse("{\"class\":\"JSONColor\",\"version\":\"1\",\"attributes\":[]}"));
        fail("no exception thrown");
    } catch (JSONException e) {
        checkJSONException(e, ERROR.JSON_TO_JAVA, "wrong attributes [", "JSONArray");
    }

    try {
        JSONTypeFactory.unwrapJSONObject(
                JSONValue.parse("{\"class\":\"ENOEXIST\",\"version\":\"12345\",\"attributes\":{}}"));
        fail("no exception thrown");
    } catch (JSONException e) {
        checkJSONException(e, ERROR.JSON_TO_JAVA, "unknown class <", "ENOEXIST", "12345");
    }
}

From source file:mml.handler.scratch.Scratch.java

protected static EcdosisMVD doGetMVD(String db, String docid) throws DbException {
    String res = null;//ww  w .  j av a 2s  . c  om
    JSONObject jDoc = null;
    res = Connector.getConnection().getFromDb(db, docid);
    if (res != null)
        jDoc = (JSONObject) JSONValue.parse(res);
    if (jDoc != null) {
        String format = (String) jDoc.get(JSONKeys.FORMAT);
        if (format != null) {
            return new EcdosisMVD(jDoc);
        }
    }
    return null;
}

From source file:az.soak.RemoteElement.java

public void loadData() throws BadLoginException, IOException {
    if (containsLoadableContent() && !isFullyLoaded()) {
        String data = performGet(getUrl());
        initWithData(JSONValue.parse(data));
        mFullyLoaded = true;//from w  ww.  ja  v a2 s .  co m
    }
}

From source file:com.p000ison.dev.simpleclans2.JSONFlags.java

@Override
public void deserialize(String jsonString) {
    if (jsonString == null || jsonString.isEmpty()) {
        return;/*from   ww w  .ja va2 s .co  m*/
    }

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

    if (flags == null) {
        return;
    }

    Set<Map.Entry> entrySet = new HashSet<Map.Entry>(flags.entrySet());

    for (Map.Entry entry : entrySet) {

        Object key = entry.getKey();
        Object value = entry.getValue();

        try {

            Object endValue = null;

            if (value instanceof JSONArray) {
                endValue = new HashSet();
                JSONArray list = (JSONArray) value;
                Set endValueSet = (Set) endValue;

                for (Object element : list) {
                    endValueSet.add(element.toString());
                }
            }

            if (endValue != null) {
                data.put(key.toString(), endValue);
            } else {
                data.put(key.toString(), value);
            }

        } catch (Exception ex) {
            Logging.debug(ex, true, "Failed at loading the flags");
        }
    }
}

From source file:foo.domaintest.config.ConfigModule.java

@Provides
@Singleton/*w  w w  .  j a  v a 2s .  co m*/
@EasterEggs
@SuppressWarnings("unchecked")
Table<String, String, String> provideEasterEggs() {
    ImmutableTable.Builder<String, String, String> table = new ImmutableTable.Builder<>();
    for (Map<String, String> egg : ((List<Map<String, String>>) JSONValue
            .parse(Optional.fromNullable(System.getProperty("foo.domaintest.eastereggs")).or("[]")))) {
        table.put(egg.get("key"), egg.get("value"), egg.get("url"));
    }
    return table.build();
}

From source file:com.janoz.tvapilib.fanarttv.impl.FanartTvImpl.java

@Override
public void addFanart(Sh show) {
    int theTvDbId = show.getTheTvDbId();
    Reader r = new InputStreamReader(openStream(getUrl(theTvDbId)));
    JSONObject showArt = (JSONObject) JSONValue.parse(r);
    //validate//from  ww  w  .  j  av a 2 s  .  c om
    String receivedTvDbId = (String) showArt.get("thetvdb_id");
    if (!receivedTvDbId.equals("" + theTvDbId)) {
        throw new TvApiException("Unexpected result. Wrong TVDB id.");
    }

    for (String key : (Set<String>) showArt.keySet()) {
        if (artMapping.containsKey(key)) {
            List<JSONObject> artArray = (List<JSONObject>) showArt.get(key);
            parsArtArray(show, key, artArray);
        }
    }
}

From source file:com.facebook.tsdb.tsdash.server.DataEndpoint.java

@Override
@SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    try {/*from  ww  w .  j  a v  a  2 s  .  co  m*/
        long ts = System.currentTimeMillis();
        // decode parameters
        String jsonParams = request.getParameter("params");
        if (jsonParams == null) {
            throw new Exception("Parameters not specified");
        }
        JSONObject jsonParamsObj = (JSONObject) JSONValue.parse(jsonParams);
        long tsFrom = (Long) jsonParamsObj.get("tsFrom");
        long tsTo = (Long) jsonParamsObj.get("tsTo");
        JSONArray metricsArray = (JSONArray) jsonParamsObj.get("metrics");
        if (metricsArray.size() == 0) {
            throw new Exception("No metrics to fetch");
        }
        MetricQuery[] metricQueries = new MetricQuery[metricsArray.size()];
        for (int i = 0; i < metricsArray.size(); i++) {
            metricQueries[i] = MetricQuery.fromJSONObject((JSONObject) metricsArray.get(i));
        }

        TsdbDataProvider dataProvider = TsdbDataProviderFactory.get();
        Metric[] metrics = new Metric[metricQueries.length];
        for (int i = 0; i < metrics.length; i++) {
            MetricQuery q = metricQueries[i];
            metrics[i] = dataProvider.fetchMetric(q.name, tsFrom, tsTo, q.tags, q.orders);
            metrics[i] = metrics[i].dissolveTags(q.getDissolveList(), q.aggregator);
            if (q.rate) {
                metrics[i].computeRate();
            }
        }
        long loadTime = System.currentTimeMillis() - ts;
        JSONObject responseObj = new JSONObject();
        JSONArray encodedMetrics = new JSONArray();
        for (Metric metric : metrics) {
            encodedMetrics.add(metric.toJSONObject());
        }
        responseObj.put("metrics", encodedMetrics);
        responseObj.put("loadtime", loadTime);
        DataTable dataTable = new DataTable(metrics);
        responseObj.put("datatable", dataTable.toJSONObject());
        out.println(responseObj.toJSONString());
        long encodingTime = System.currentTimeMillis() - ts - loadTime;
        logger.info("[Data] time frame: " + (tsTo - tsFrom) + "s, " + "load time: " + loadTime + "ms, "
                + "encoding time: " + encodingTime + "ms");
    } catch (Exception e) {
        out.println(getErrorResponse(e));
    }
    out.close();
}