Example usage for org.json.simple JSONObject get

List of usage examples for org.json.simple JSONObject get

Introduction

In this page you can find the example usage for org.json.simple JSONObject get.

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:JavaCloud.Utils.java

public static Object request(String address, String function, final JSONObject params) throws CoreException {
    try {/*from  w  ww . ja va 2s .com*/
        GenericUrl url = new GenericUrl(address + "/" + function);
        NetHttpTransport transport = new NetHttpTransport();
        HttpRequest request = transport.createRequestFactory().buildPostRequest(url, new HttpContent() {
            @Override
            public long getLength() throws IOException {
                return params.toString().length();
            }

            @Override
            public String getType() {
                return "text/json";
            }

            @Override
            public boolean retrySupported() {
                return false;
            }

            @Override
            public void writeTo(OutputStream outputStream) throws IOException {
                outputStream.write(params.toString().getBytes());
            }
        });
        HttpResponse response = request.execute();
        JSONParser parser = new JSONParser();
        JSONObject object = (JSONObject) parser.parse(response.parseAsString());

        if (!object.get("status").equals("ok")) {
            throw new CoreException(object.get("status").toString());
        }

        if (object.containsKey("data") && object.get("data") != null)
            return parser.parse(object.get("data").toString());
        else
            return null;
    } catch (ParseException e) {
        System.out.println("Error parsing response: " + e.toString());
        throw new CoreException("json_malformed");
    } catch (IOException e) {
        System.out.println("Error connecting to server: " + e.toString());
        throw new CoreException("connection_failed");
    }
}

From source file:myproject.MyServer.java

public static void Delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {/*from www. ja v  a 2 s .c  om*/
        String jsonString = IOUtils.toString(request.getInputStream());
        JSONObject json = (JSONObject) JSONValue.parse(jsonString);
        Long student_id = (Long) json.get("student_id");

        String query = String.format("DELETE FROM student " + "WHERE student_id=%d", student_id);

        database.runUpdate(query);

        JSONObject output = new JSONObject();
        output.put("result", true);
        response.getWriter().write(JSONValue.toJSONString(output));
    } catch (Exception ex) {
        JSONObject output = new JSONObject();
        output.put("error", "Connection failed: " + ex.getMessage());
        response.getWriter().write(JSONValue.toJSONString(output));
    }
}

From source file:autoancillarieslimited.parser.ParserUtil.java

public static Employee parserEmployeeFromJSON(String dataJson) {
    try {//from   w  w  w. j  ava 2  s.co  m
        Employee i = new Employee();
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(dataJson);
        JSONObject jsonObject = (JSONObject) obj;
        int id = Integer.parseInt((String) jsonObject.get("P0"));
        int warehouse_id = Integer.parseInt((String) jsonObject.get("P1"));
        String email = (String) jsonObject.get("P2");
        String password = (String) jsonObject.get("P3");
        String name = (String) jsonObject.get("P4");
        String address = (String) jsonObject.get("P5");
        String phone = (String) jsonObject.get("P6");
        i.setId(id);
        i.setEmail(email);
        i.setPassword(password);
        i.setName(name);
        i.setAddress(address);
        i.setPhone(phone);
        WareHouses houses = WareHousesDAO.getInstance().getByID(warehouse_id, WareHouses.class);
        i.setWareHouses(houses);
        return i;
    } catch (Exception ex) {
        return null;
    }
}

From source file:autoancillarieslimited.parser.ParserUtil.java

public static Item parserItem(String dataJson) {
    try {//from   w  w w.  j a  v  a 2s.com
        Item i = new Item();
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(dataJson);
        JSONObject jsonObject = (JSONObject) obj;
        int id = Integer.parseInt((String) jsonObject.get("P0"));
        String name = (String) jsonObject.get("P1");
        String description = (String) jsonObject.get("P3");
        int category = Integer.parseInt((String) jsonObject.get("P2"));
        double price = Double.parseDouble((String) jsonObject.get("P4"));
        String images = (String) jsonObject.get("P6");
        //     String imagesData
        i.setId(id);
        i.setName(name);
        i.setDescription(description);
        i.setPrice(price);
        i.setDate_Created(new Date());
        TypeItem typeItemByID = ProductDAO.getInstance().getTypeItemByID(category);
        i.setTypeItem(typeItemByID);
        i.setType_ID(category);
        i.setImages(images);
        return i;
    } catch (Exception ex) {
        return null;
    }
}

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

/**
 * Finds the manga JSON object from the array
 * based on the manga id provided./*  ww  w .  ja va  2s. c  o  m*/
 * 
 * @param jsonMangas the array
 * @param mangaId the manga id
 * @return the manga, if found
 */
protected static JSONObject findManga(JSONArray jsonMangas, String mangaId) {
    for (int i = 0; i < jsonMangas.size(); i++) {
        JSONObject jsonManga = (JSONObject) jsonMangas.get(i);
        Object id = jsonManga == null ? null : jsonManga.get("id");
        if (id.equals(mangaId))
            return jsonManga;
    }
    return null;
}

From source file:iracing.webapi.SessionResultDriverLapsParser.java

static SessionResultDriverLaps parse(String json) {
    JSONParser parser = new JSONParser();
    SessionResultDriverLaps output = null;
    try {//from   w ww  . j  a  v  a 2s.co 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:com.baystep.jukeberry.JsonConfiguration.java

public static int getInt(JSONObject obj, String key) {
    return castLongToInt((long) obj.get(key));
}

From source file:ch.uzh.phys.ecn.oboma.map.api.MapFactory.java

public static INodeMap buildDefaultSBBMap() throws Exception {
    NodeMap map = new NodeMap();
    Random rand = new Random();
    int stationCount = 0;
    int trainCount = 0;

    JSONParser parser = new JSONParser();

    try {/*from w ww  .  j  a v  a 2  s . co m*/
        JSONArray stations = (JSONArray) parser.parse(Files.newBufferedReader(Paths.get("data/stations.json")));
        for (Object o : stations) {
            JSONObject station = (JSONObject) o;

            String id = (String) station.get("id");
            String name = (String) station.get("name");
            JSONObject coord = (JSONObject) ((JSONObject) station.get("location")).get("wgs");
            Double lat = (Double) coord.get("y");
            Double lng = (Double) coord.get("x");

            Node node = new Node(id, name, lat, lng, 0, 0);
            map.add(node);
            stationCount++;

            LOGGER.info(String.format("Station Node %s (%s) added", id, name));
        }

        JSONArray connections = (JSONArray) parser
                .parse(Files.newBufferedReader(Paths.get("data/connections.json")));
        for (Object o : connections) {
            JSONObject connection = (JSONObject) o;

            String from = (String) connection.get("from");
            String to = (String) connection.get("to");
            int time = (int) ((long) connection.get("time"));

            String id1 = String.format("%s-%s", from, to);
            String name1 = String.format("Train %s - %s", from, to);
            String id2 = String.format("%s-%s", to, from);
            String name2 = String.format("Train %s - %s", to, from);
            int seats = rand.nextInt(1000) + 1;

            Node node1 = new TrainNode(id1, name1, 0, 0, time, seats);
            Node node2 = new TrainNode(id2, name2, 0, 0, time, seats);
            try {
                map.add(node1, from, to);
                map.add(node2, to, from);
                trainCount++;
                LOGGER.info(String.format("Train Node %s (%s -> %s) added (%d seats)", id1, from, to, seats));
            } catch (Exception pEx) {
                // either from or to do not exist
            }
        }

        LOGGER.info(String.format("%d stations added / %d trains added", stationCount, trainCount));
    } catch (Exception pEx) {
        throw new Exception("Could not build map", pEx);
    }

    return map;
}

From source file:myproject.MyServer.java

public static void Update(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {/*www  .  j ava  2s.com*/
        String jsonString = IOUtils.toString(request.getInputStream());
        JSONObject json = (JSONObject) JSONValue.parse(jsonString);
        Long student_id = (Long) json.get("student_id");
        String student_name = (String) json.get("student_name");
        Long regno = (Long) json.get("regno");
        Double cgpa = (Double) json.get("cgpa");

        String query = String.format(
                "UPDATE student " + "SET student_name='%s'," + "regno=%d," + "cgpa=%f " + "WHERE student_id=%d",
                JSONValue.escape(student_name), regno, cgpa, student_id);

        database.runUpdate(query);

        String result = database.getStudent(regno);
        response.getWriter().write(result);
    } catch (Exception ex) {
        JSONObject output = new JSONObject();
        output.put("error", "Connection failed: " + ex.getMessage());
        response.getWriter().write(JSONValue.toJSONString(output));
    }
}

From source file:com.AandC.GemsCraft.Configuration.ConfigKey.java

public static String getMOTD() {
    try {/*from  ww  w .j  av  a  2 s. c o  m*/
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(new FileReader("/sdcard/GemsCraft/config.json"));
        JSONObject jsonObject = (JSONObject) obj;
        MOTD = String.valueOf(jsonObject.get("MOTD"));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return MOTD;
}