Example usage for org.json JSONObject toString

List of usage examples for org.json JSONObject toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Make a JSON text of this JSONObject.

Usage

From source file:edu.stanford.junction.provider.irc.Junction.java

@Override
public void doSendMessageToActor(String actorID, JSONObject message) {
    sendMsgTo(message.toString(), actorID);
}

From source file:edu.stanford.junction.provider.irc.Junction.java

@Override
public void doSendMessageToRole(String role, JSONObject message) {
    JSONObject jx;// ww  w . j  a v  a 2 s  . c  om
    if (message.has(NS_JX)) {
        jx = message.optJSONObject(NS_JX);
    } else {
        jx = new JSONObject();
        try {
            message.put(NS_JX, jx);
        } catch (JSONException j) {
        }
    }
    try {
        jx.put("targetRole", role);
    } catch (Exception e) {
    }

    String msg = message.toString();
    sendMsgTo(msg, "#" + mSession + "," + mNickname);
}

From source file:edu.stanford.junction.provider.irc.Junction.java

@Override
public void doSendMessageToSession(JSONObject message) {
    String msg = message.toString();
    sendMsgTo(msg, "#" + mSession + "," + mNickname);
}

From source file:com.mobiperf_library.util.MeasurementJsonConvertor.java

public static MeasurementTask makeMeasurementTaskFromJson(JSONObject json) throws IllegalArgumentException {
    try {//from   w ww . j  av a 2  s .c  o m
        String type = String.valueOf(json.getString("type"));
        Class taskClass = MeasurementTask.getTaskClassForMeasurement(type);
        Method getDescMethod = taskClass.getMethod("getDescClass");
        // The getDescClassForMeasurement() is static and takes no arguments
        Class descClass = (Class) getDescMethod.invoke(null, (Object[]) null);
        MeasurementDesc measurementDesc = (MeasurementDesc) gson.fromJson(json.toString(), descClass);

        Object cstParam = measurementDesc;
        Constructor<MeasurementTask> constructor = taskClass.getConstructor(MeasurementDesc.class);
        return constructor.newInstance(cstParam);
    } catch (JSONException e) {
        throw new IllegalArgumentException(e);
    } catch (SecurityException e) {
        Logger.w(e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (NoSuchMethodException e) {
        Logger.w(e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (IllegalArgumentException e) {
        Logger.w(e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (InstantiationException e) {
        Logger.w(e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (IllegalAccessException e) {
        Logger.w(e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (InvocationTargetException e) {
        Logger.w(e.toString());
        throw new IllegalArgumentException(e);
    }
}

From source file:com.shampan.services.SearchService.java

/**
 * This method will return users/* w  w  w. j a  va2  s . c o m*/
 *
 * @param requestPatten, request String
 * @return users
 */
public static String getSearchResult(String searchValue, int offset, int limit) {
    JSONObject searchResult = new JSONObject();
    searchResult.put("userList", searchModel.getUsers(searchValue, offset, limit));
    searchResult.put("pageList", searchModel.getPages(searchValue, offset, limit));
    return searchResult.toString();
}

From source file:edu.mit.scratch.ScratchProject.java

public boolean comment(final ScratchSession session, final String comment) throws ScratchProjectException {
    final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

    final CookieStore cookieStore = new BasicCookieStore();
    final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
    final BasicClientCookie sessid = new BasicClientCookie("scratchsessionsid", session.getSessionID());
    final BasicClientCookie token = new BasicClientCookie("scratchcsrftoken", session.getCSRFToken());
    final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
    lang.setDomain(".scratch.mit.edu");
    lang.setPath("/");
    sessid.setDomain(".scratch.mit.edu");
    sessid.setPath("/");
    token.setDomain(".scratch.mit.edu");
    token.setPath("/");
    debug.setDomain(".scratch.mit.edu");
    debug.setPath("/");
    cookieStore.addCookie(lang);//from   w  w  w.  j a v a  2s.  c  o m
    cookieStore.addCookie(sessid);
    cookieStore.addCookie(token);
    cookieStore.addCookie(debug);

    final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
            .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64)"
                    + " AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/" + "537.36")
            .setDefaultCookieStore(cookieStore).build();
    CloseableHttpResponse resp;

    final JSONObject obj = new JSONObject();
    obj.put("content", comment);
    obj.put("parent_id", "");
    obj.put("commentee_id", "");
    final String strData = obj.toString();

    HttpUriRequest update = null;
    try {
        update = RequestBuilder.post()
                .setUri("https://scratch.mit.edu/site-api/comments/project/" + this.getProjectID() + "/add/")
                .addHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .addHeader("Referer", "https://scratch.mit.edu/projects/" + this.getProjectID() + "/")
                .addHeader("Origin", "https://scratch.mit.edu/")
                .addHeader("Accept-Encoding", "gzip, deflate, sdch")
                .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json")
                .addHeader("X-Requested-With", "XMLHttpRequest")
                .addHeader("Cookie",
                        "scratchsessionsid=" + session.getSessionID() + "; scratchcsrftoken="
                                + session.getCSRFToken())
                .addHeader("X-CSRFToken", session.getCSRFToken()).setEntity(new StringEntity(strData)).build();
    } catch (final UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }
    try {
        resp = httpClient.execute(update);
        System.out.println("cmntadd:" + resp.getStatusLine());
        final BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        System.out.println("cmtline:" + result.toString());
    } catch (final IOException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }

    BufferedReader rd;
    try {
        rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
    } catch (UnsupportedOperationException | IOException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }

    return false;
}

From source file:net.dv8tion.jda.core.handle.MessageUpdateHandler.java

public void handleCallMessage(JSONObject content) {
    WebSocketClient.LOG.debug("Received a MESSAGE_UPDATE of type CALL:  " + content.toString());
    //Called when someone joins call for first time.
    //  It is not called when they leave or rejoin. That is all dictated by VOICE_STATE_UPDATE.
    //  Probably can ignore the above due to VOICE_STATE_UPDATE
    // Could have a mapping of all users who were participants at one point or another during the call
    //  in comparison to the currently participants.
    // and when the call is ended. Ending defined by ended_timestamp != null
}

From source file:com.mobile.system.db.abatis.AbatisService.java

/**
 * //from   ww  w . j  ava  2 s . co m
 * @param jsonStr
 *            JSON String
 * @param beanClass
 *            Bean class
 * @param basePackage
 *            Base package name which includes all Bean classes
 * @return Object Bean
 * @throws Exception
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public Object parse(String jsonStr, Class beanClass, String basePackage) throws Exception {
    Object obj = null;
    JSONObject jsonObj = new JSONObject(jsonStr);
    // Check bean object
    if (beanClass == null) {
        Log.d(TAG, "Bean class is null");
        return null;
    }
    // Read Class member fields
    Field[] props = beanClass.getDeclaredFields();
    if (props == null || props.length == 0) {
        Log.d(TAG, "Class" + beanClass.getName() + " has no fields");
        return null;
    }
    // Create instance of this Bean class
    obj = beanClass.newInstance();
    // Set value of each member variable of this object
    for (int i = 0; i < props.length; i++) {
        String fieldName = props[i].getName();
        // Skip public and static fields
        if (props[i].getModifiers() == (Modifier.PUBLIC | Modifier.STATIC)) {
            continue;
        }
        // Date Type of Field
        Class type = props[i].getType();
        String typeName = type.getName();
        // Check for Custom type
        if (typeName.equals("int")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getInt(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("long")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getLong(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("java.lang.String")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getString(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("double")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getDouble(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("java.util.Date")) { // modify

            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);

            String dateString = jsonObj.getString(fieldName);
            dateString = dateString.replace(" KST", "");
            SimpleDateFormat genderFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy", Locale.KOREA);
            // Set value
            try {
                Date afterDate = genderFormat.parse(dateString);
                m.invoke(obj, afterDate);
            } catch (Exception e) {
                Log.d(TAG, e.getMessage());
            }
        } else if (type.getName().equals(List.class.getName())
                || type.getName().equals(ArrayList.class.getName())) {
            // Find out the Generic
            String generic = props[i].getGenericType().toString();
            if (generic.indexOf("<") != -1) {
                String genericType = generic.substring(generic.lastIndexOf("<") + 1, generic.lastIndexOf(">"));
                if (genericType != null) {
                    JSONArray array = null;
                    try {
                        array = jsonObj.getJSONArray(fieldName);
                    } catch (Exception ex) {
                        Log.d(TAG, ex.getMessage());
                        array = null;
                    }
                    if (array == null) {
                        continue;
                    }
                    ArrayList arrayList = new ArrayList();
                    for (int j = 0; j < array.length(); j++) {
                        arrayList.add(parse(array.getJSONObject(j).toString(), Class.forName(genericType),
                                basePackage));
                    }
                    // Set value
                    Class[] parms = { type };
                    Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
                    m.setAccessible(true);
                    m.invoke(obj, arrayList);
                }
            } else {
                // No generic defined
                generic = null;
            }
        } else if (typeName.startsWith(basePackage)) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                JSONObject customObj = jsonObj.getJSONObject(fieldName);
                if (customObj != null) {
                    m.invoke(obj, parse(customObj.toString(), type, basePackage));
                }
            } catch (JSONException ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else {
            // Skip
            Log.d(TAG, "Field " + fieldName + "#" + typeName + " is skip");
        }
    }
    return obj;
}

From source file:org.cloudfoundry.client.lib.util.JsonUtil.java

public static Map<String, Object> convertJsonToMap(JSONObject json) throws JSONException {
    Map<String, Object> retMap = new HashMap<String, Object>();
    JSONObject jo = new JSONObject(json.toString());
    for (String key : JsonUtil.keys(jo)) {
        if (jo.get(key.toString()) instanceof JSONObject) {
            retMap.put(key.toString(), convertJsonToMap(jo.getJSONObject(key.toString())));
        } else {// w  w w .  j av  a  2  s  .co  m
            retMap.put(key.toString(), jo.getString(key.toString()));
        }
    }
    return retMap;
}

From source file:com.layer.atlas.messenger.AtlasIdentityProvider.java

private String[] refreshContacts(boolean requestIdentityToken, String nonce, String userName) {
    try {/*www  .  ja  va  2  s. c o  m*/
        String url = "https://layer-identity-provider.herokuapp.com/apps/" + appId + "/atlas_identities";
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type", "application/json");
        post.setHeader("Accept", "application/json");
        post.setHeader("X_LAYER_APP_ID", appId);

        JSONObject rootObject = new JSONObject();
        if (requestIdentityToken) {
            rootObject.put("nonce", nonce);
            rootObject.put("name", userName);
        } else {
            rootObject.put("name", "Web"); // name must be specified to make entiry valid
        }
        StringEntity entity = new StringEntity(rootObject.toString(), "UTF-8");
        entity.setContentType("application/json");
        post.setEntity(entity);

        HttpResponse response = (new DefaultHttpClient()).execute(post);
        if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()
                && HttpStatus.SC_CREATED != response.getStatusLine().getStatusCode()) {
            StringBuilder sb = new StringBuilder();
            sb.append("Got status ").append(response.getStatusLine().getStatusCode()).append(" [")
                    .append(response.getStatusLine()).append("] when logging in. Request: ").append(url);
            if (requestIdentityToken)
                sb.append(" login: ").append(userName).append(", nonce: ").append(nonce);
            Log.e(TAG, sb.toString());
            return new String[] { null, sb.toString() };
        }

        String responseString = EntityUtils.toString(response.getEntity());
        JSONObject jsonResp = new JSONObject(responseString);

        JSONArray atlasIdentities = jsonResp.getJSONArray("atlas_identities");
        List<Participant> participants = new ArrayList<Participant>(atlasIdentities.length());
        for (int i = 0; i < atlasIdentities.length(); i++) {
            JSONObject identity = atlasIdentities.getJSONObject(i);
            Participant participant = new Participant();
            participant.firstName = identity.getString("name");
            participant.userId = identity.getString("id");
            participants.add(participant);
        }
        if (participants.size() > 0) {
            setParticipants(participants);
            save();
            if (debug)
                Log.d(TAG, "refreshContacts() contacts: " + atlasIdentities);
        }

        if (requestIdentityToken) {
            String error = jsonResp.optString("error", null);
            String identityToken = jsonResp.optString("identity_token");
            return new String[] { identityToken, error };
        }
        return new String[] { null, "Refreshed " + participants.size() + " contacts" };
    } catch (Exception e) {
        Log.e(TAG, "Error when fetching identity token", e);
        return new String[] { null, "Cannot obtain identity token. " + e };
    }
}