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:org.kitodo.data.elasticsearch.index.type.WorkpieceTypeTest.java

@Test
public void shouldCreateDocument() throws Exception {
    WorkpieceType workpieceType = new WorkpieceType();
    JSONParser parser = new JSONParser();

    Workpiece workpiece = prepareData().get(0);
    HttpEntity document = workpieceType.createDocument(workpiece);
    JSONObject actual = (JSONObject) parser.parse(EntityUtils.toString(document));
    JSONObject expected = (JSONObject) parser.parse("{\"process\":1,\"properties\":[{\"id\":1},{\"id\":2}]}");
    assertEquals("Workpiece value for process key doesn't match to given plain text!", expected, actual);

    workpiece = prepareData().get(1);/*from   w w  w.  java2  s  .c o m*/
    document = workpieceType.createDocument(workpiece);
    actual = (JSONObject) parser.parse(EntityUtils.toString(document));
    expected = (JSONObject) parser.parse("{\"process\":2,\"properties\":[]}");
    assertEquals("Workpiece value for process key doesn't match to given plain text!", expected, actual);
}

From source file:com.optimizely.ab.config.parser.JsonSimpleConfigParser.java

@Override
public ProjectConfig parseProjectConfig(@Nonnull String json) throws ConfigParseException {
    try {//from  ww  w.ja va  2s  . c  om
        JSONParser parser = new JSONParser();
        JSONObject rootObject = (JSONObject) parser.parse(json);

        String accountId = (String) rootObject.get("accountId");
        String projectId = (String) rootObject.get("projectId");
        String revision = (String) rootObject.get("revision");
        String version = (String) rootObject.get("version");

        List<Experiment> experiments = parseExperiments((JSONArray) rootObject.get("experiments"));
        List<Attribute> attributes = parseAttributes((JSONArray) rootObject.get("dimensions"));
        List<EventType> events = parseEvents((JSONArray) rootObject.get("events"));
        List<Audience> audiences = parseAudiences(
                (JSONArray) parser.parse(rootObject.get("audiences").toString()));
        List<Group> groups = parseGroups((JSONArray) rootObject.get("groups"));

        return new ProjectConfig(accountId, projectId, version, revision, groups, experiments, attributes,
                events, audiences);
    } catch (ParseException e) {
        throw new ConfigParseException("unable to parse project config: " + json, e);
    }
}

From source file:org.kitodo.data.elasticsearch.index.type.HistoryTypeTest.java

@Test
public void shouldCreateDocument() throws Exception {
    HistoryType historyType = new HistoryType();
    JSONParser parser = new JSONParser();

    History history = prepareData().get(0);
    HttpEntity document = historyType.createDocument(history);
    JSONObject actual = (JSONObject) parser.parse(EntityUtils.toString(document));
    JSONObject expected = (JSONObject) parser.parse("{\"date\":\"2017-01-14\",\"numericValue\":1.0,"
            + "\"stringValue\":\"1\",\"process\":1,\"type\":0}");
    assertEquals("History JSONObject doesn't match to given JSONObject!", expected, actual);

    history = prepareData().get(1);//from w  ww  .  j  ava2s  .  com
    document = historyType.createDocument(history);
    actual = (JSONObject) parser.parse(EntityUtils.toString(document));
    expected = (JSONObject) parser
            .parse("{\"date\":null,\"numericValue\":2.0,\"stringValue\":\"2\"," + "\"process\":2,\"type\":12}");
    assertEquals("History JSONObject doesn't match to given JSONObject!", expected, actual);
}

From source file:org.opencastproject.adminui.endpoint.TasksEndpointTest.java

@Test
public void testGetProcessing() throws ParseException, IOException {
    InputStream stream = TasksEndpointTest.class.getResourceAsStream("/taskProcessing.json");
    InputStreamReader reader = new InputStreamReader(stream);
    JSONArray expected = (JSONArray) new JSONParser().parse(reader);
    JSONArray actual = (JSONArray) parser
            .parse(given().queryParam("tags", "archive").expect().log().all().statusCode(HttpStatus.SC_OK)
                    .contentType(ContentType.JSON).when().get(rt.host("/processing.json")).asString());

    Assert.assertEquals(expected.size(), actual.size());
}

From source file:com.nubits.nubot.pricefeeds.feedservices.BitcoinaveragePriceFeed.java

@Override
public LastPrice getLastPrice(CurrencyPair pair) {

    long now = System.currentTimeMillis();
    long diff = now - lastRequest;
    if (diff >= refreshMinTime) {
        String htmlString;//from w w w  . j a  v a 2 s  . com
        try {
            htmlString = Utils.getHTML(getUrl(pair), true);
        } catch (IOException ex) {
            LOG.error(ex.toString());
            return new LastPrice(true, name, pair.getOrderCurrency(), null);
        }
        JSONParser parser = new JSONParser();
        try {
            JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString));
            double last = Utils.getDouble(httpAnswerJson.get("last"));
            lastRequest = System.currentTimeMillis();
            lastPrice = new LastPrice(false, name, pair.getOrderCurrency(),
                    new Amount(last, pair.getPaymentCurrency()));
            return lastPrice;
        } catch (Exception ex) {
            LOG.error(ex.toString());
            lastRequest = System.currentTimeMillis();
            return new LastPrice(true, name, pair.getOrderCurrency(), null);
        }
    } else {
        double t = (refreshMinTime - (System.currentTimeMillis() - lastRequest));
        LOG.warn("Wait " + t + " ms " + "before making a new request. Now returning the last saved price\n\n");
        return lastPrice;
    }

}

From source file:edu.ncsu.epc.models.GetInfo.java

public ApartmentInfo parseJSON(String response, String addr) {
    ApartmentInfo aptInfo = null;//from w ww  . j a  va  2s. c  om
    try {
        JSONObject json = (JSONObject) new JSONParser().parse(response);
        JSONArray jsonArray = (JSONArray) new JSONParser().parse(json.get("collection").toString());
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject json2 = (JSONObject) new JSONParser().parse(jsonArray.get(i).toString());
            if (addr.startsWith(json2.get("address").toString())) {
                aptInfo = new ApartmentInfo();
                aptInfo.addr = json2.get("address").toString();
                if (json2.get("city") != null)
                    aptInfo.city = json2.get("city").toString();
                if (json2.get("state") != null)
                    aptInfo.state = json2.get("state").toString();
                if (json2.get("bedrooms") == null) {
                    JSONArray jsonArray1 = (JSONArray) new JSONParser()
                            .parse(json2.get("latest_prices").toString());
                    JSONObject jsonlatest_price = (JSONObject) new JSONParser()
                            .parse(jsonArray1.get(0).toString());
                    aptInfo.noOfBedrooms = Double.parseDouble(jsonlatest_price.get("bedrooms").toString());
                    aptInfo.rent = Double.parseDouble(jsonlatest_price.get("rent").toString());
                } else {
                    aptInfo.noOfBedrooms = Double.parseDouble(json2.get("bedrooms").toString());
                    aptInfo.rent = Double.parseDouble(json2.get("rent").toString());
                }
                if (json2.get("rent") != null)
                    aptInfo.rent = Double.parseDouble(json2.get("rent").toString());
                aptInfo.zip = (String) json2.get("zip_code");
                if (json2.get("year_built") != null)
                    aptInfo.year_built = Double.parseDouble(json2.get("year_built").toString());

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return aptInfo;
}

From source file:iracing.webapi.SessionResultDriverLapsParser.java

static SessionResultDriverLaps parse(String json) {
    JSONParser parser = new JSONParser();
    SessionResultDriverLaps output = null;
    try {//from  ww  w.jav  a 2 s .c o m
        JSONObject root = (JSONObject) parser.parse(json);
        output = new SessionResultDriverLaps();
        JSONObject details = (JSONObject) root.get("details");
        output.setLapsForSolo(getInt(details, "nlapsforsolo"));
        output.setBestNLapsNumber(getInt(details, "bestnlapsnum"));
        output.setSeasonShortName(getString(details, "seasonShortName", true));
        output.setMaximumLicenseLevel(getInt(details, "maxLicenseLevel"));
        output.setDriverName(getString(details, "displayname", true));
        output.setSeasonName(getString(details, "seasonName", true));
        output.setSeriesName(getString(details, "seriesName", true));
        output.setSeriesShortName(getString(details, "seriesShortName", true));
        output.setSessionId(getLong(details, "sessionId"));
        output.setSubSessionId(getLong(details, "subSessionId"));
        output.setCarNumber(getString(details, "carNum"));
        output.setCarId(getInt(details, "carid"));
        output.setEventTypeId(getInt(details, "eventtype"));
        output.setEventTypeName(getString(details, "eventTypeName", true));
        output.setBestQualifyingLapAt(getInt(details, "bestQualLapAt"));
        output.setBestQualifyingLapNumber(getInt(details, "bestQualLapNum"));
        output.setBestLapNumber(getInt(details, "bestLapNum"));
        output.setBestNLapsTime(getInt(details, "bestNLapsTime"));
        output.setLapsForQualifying(getInt(details, "nlapsforqual"));
        output.setBestQualifyingLapTime(getLong(details, "bestQualLapTime"));
        output.setTrackId(getInt(details, "trackID"));
        output.setTrackName(getString(details, "trackName", true));
        output.setTrackConfigName(getString(details, "trackConfig", true));
        output.setEventDate(new Date(getLong(details, "eventDateUTCMilliSecs")));
        List<SessionResultDriverLap> lapList = new ArrayList<SessionResultDriverLap>();
        JSONArray a = (JSONArray) root.get("laps");
        long lastLapTime = 0;
        for (int i = 0; i < a.size(); i++) {
            JSONObject r = (JSONObject) a.get(i);
            SessionResultDriverLap d = new SessionResultDriverLap();
            d.setLapNumber(getInt(r, "lapnum"));
            long lapTime = getLong(r, "time");
            d.setLapTime(lapTime - lastLapTime);
            lastLapTime = lapTime;
            d.setFlags(getInt(r, "flags"));
            lapList.add(d);
        }
        output.setLaps(lapList);
    } catch (ParseException ex) {
        Logger.getLogger(SessionResultDriverLapsParser.class.getName()).log(Level.SEVERE, null, ex);
    }
    return output;
}

From source file:cc.pinel.mangue.storage.AbstractStorage.java

/**
 * Reads the storage JSON./*ww w  .ja v  a2s .c  o m*/
 * 
 * @return the JSON object
 * @throws ParseException
 * @throws IOException
 */
protected JSONObject readJSON() throws ParseException, IOException {
    InputStream is = getClass().getResourceAsStream(getPath());

    JSONParser parser = new JSONParser();

    return (JSONObject) parser.parse(IOUtils.toString(is));
}

From source file:processingtest.CitySense.java

public ArrayList<CityData> getDayDataByLocation() throws IOException {
    String query = queryBuilder.getDayDataByLocation(2); //Over 2 days
    CloseableHttpResponse response = this.executeRequest(query);
    HttpEntity entity = response.getEntity();
    ArrayList<CityData> dataPoints = null;

    if (entity != null) {
        try ( // A Simple JSON Response Read
                InputStream instream = entity.getContent()) {
            String result = convertStreamToString(instream);
            // now you have the string representation of the HTML request
            //System.out.println("RESPONSE: " + result);

            JSONParser parser = new JSONParser();
            try {
                Object obj = parser.parse(result);
                JSONObject jobj = (JSONObject) obj;
                //System.out.println(jobj.entrySet());
                Object dataObject = jobj.get("data");
                JSONArray array = (JSONArray) dataObject;
                //System.out.println(array.get(0));
                dataPoints = decodeJsonData(array);
                System.out.println((dataPoints.size()));
            } catch (ParseException pe) {
                System.out.println("position: " + pe.getPosition());
                System.out.println(pe);
            }/*from   w  w w  .j av a  2s  . co  m*/
        }
    }
    return dataPoints;
}

From source file:com.nubits.nubot.pricefeeds.feedservices.BitstampPriceFeed.java

@Override
public LastPrice getLastPrice(CurrencyPair pair) {
    long now = System.currentTimeMillis();
    long diff = now - lastRequest;
    if (diff >= refreshMinTime) {
        String url = "https://www.bitstamp.net/api/ticker/";
        String htmlString;//from   w w w .jav  a  2s .c  om
        try {
            htmlString = Utils.getHTML(url, true);
        } catch (IOException ex) {
            LOG.error(ex.toString());
            return new LastPrice(true, name, pair.getOrderCurrency(), null);
        }
        JSONParser parser = new JSONParser();
        try {
            JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString));
            double last = Double.valueOf((String) httpAnswerJson.get("last"));

            //Make the average between buy and sell
            last = Utils.round(last, 8);

            lastRequest = System.currentTimeMillis();
            lastPrice = new LastPrice(false, name, pair.getOrderCurrency(),
                    new Amount(last, pair.getPaymentCurrency()));
            return lastPrice;
        } catch (Exception ex) {
            LOG.error(ex.toString());
            lastRequest = System.currentTimeMillis();
            return new LastPrice(true, name, pair.getOrderCurrency(), null);
        }
    } else {
        LOG.warn("Wait " + (refreshMinTime - (System.currentTimeMillis() - lastRequest)) + " ms "
                + "before making a new request. Now returning the last saved price\n\n");
        return lastPrice;
    }
}