Example usage for org.json JSONTokener JSONTokener

List of usage examples for org.json JSONTokener JSONTokener

Introduction

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

Prototype

public JSONTokener(String s) 

Source Link

Document

Construct a JSONTokener from a string.

Usage

From source file:com.whizzosoftware.hobson.dto.property.PropertyContainerDTOTest.java

@Test
public void testJSONConstructor2() {
    JSONObject json = new JSONObject(new JSONTokener(
            "{\"cclass\":{\"@id\":\"/api/v1/hubs/local/plugins/com.whizzosoftware.hobson.hub.hobson-hub-rules/conditionClasses/turnOn\"},\"values\":{\"devices\":[{\"@id\":\"/api/v1/hubs/local/plugins/com.whizzosoftware.hobson.hub.hobson-hub-sample/devices/bulb\"}]}}"));
    PropertyContainerDTO dto = new PropertyContainerDTO.Builder(json).build();
    assertEquals(1, dto.getValues().size());
}

From source file:com.whizzosoftware.hobson.dto.property.PropertyContainerDTOTest.java

@Test
public void testJSONConstructorWithJSONObjectValue() {
    JSONObject json = new JSONObject(new JSONTokener(
            "{\"id\":\"/api/v1/hubs/local/plugins/local/com.whizzosoftware.hobson.hub.hobson-hub-wunderground\",\"values\":{\"pwsPassword\":\"password\",\"pwsId\":\"MYID\",\"device\":{\"@id\":\"/api/v1/hubs/local/plugins/com.whizzosoftware.hobson.hub.hobson-hub-davis-vantage/devices/default\"},\"serial.hostname\":\"192.168.0.1\"},\"cclass\":{\"@id\":\"/api/v1/hubs/local/plugins/local/com.whizzosoftware.hobson.hub.hobson-hub-wunderground/configurationClass\"},\"url\":\"/api/v1/hubs/local/plugins/local/com.whizzosoftware.hobson.hub.hobson-hub-wunderground/configuration\"}"));
    PropertyContainerDTO dto = new PropertyContainerDTO.Builder(json).build();
    assertEquals("password", dto.getValues().get("pwsPassword"));
    assertEquals("MYID", dto.getValues().get("pwsId"));
    assertEquals("192.168.0.1", dto.getValues().get("serial.hostname"));
    assertTrue(dto.getValues().get("device") instanceof JSONObject);
    assertEquals(//w ww  .  j a v  a2  s  . c o m
            "/api/v1/hubs/local/plugins/com.whizzosoftware.hobson.hub.hobson-hub-davis-vantage/devices/default",
            ((JSONObject) dto.getValues().get("device")).getString("@id"));
}

From source file:com.whizzosoftware.hobson.dto.property.PropertyContainerDTOTest.java

@Test
public void testNullValue() {
    JSONObject json = new JSONObject(new JSONTokener(
            "{\"cclass\":{\"@id\":\"/api/v1/users/local/hubs/local/plugins/plugin1/actionClasses/actionclass1\"},\"values\":{\"foo\":null}}"));
    PropertyContainerDTO dto = new PropertyContainerDTO.Builder(json).build();
    assertTrue(dto.hasPropertyValues());
    assertEquals(1, dto.getValues().size());
    assertNull(dto.getValues().get("foo"));
}

From source file:com.f16gaming.pathofexilestatistics.PoeEntry.java

public static PoeEntry[] getEntriesFromJSONString(String jsonData) throws JSONException {
    JSONObject root = (JSONObject) new JSONTokener(jsonData).nextValue();
    JSONObject ladder = root.getJSONObject("ladder");
    JSONArray entries = ladder.getJSONArray("entries");
    int length = entries.length();
    PoeEntry[] result = new PoeEntry[length];
    for (int i = 0; i < length; i++) {
        JSONObject entry = entries.getJSONObject(i);
        String account = entry.getJSONObject("account").getString("name");
        int rank = entry.getInt("rank");
        JSONObject character = entry.getJSONObject("character");
        String name = character.getString("name");
        int level = character.getInt("level");
        boolean online = entry.getBoolean("online");
        String className = character.getString("class");
        long experience = character.getLong("experience");
        PoeEntry poeEntry = new PoeEntry(account, rank, name, level, online, className, experience);
        result[i] = poeEntry;/* ww  w.  j  a v  a2s  .co  m*/
    }
    return result;
}

From source file:com.tassadar.multirommgr.installfragment.UbuntuChannel.java

public boolean loadDeviceImages(String device_name, Device dev) throws Exception {
    String path = m_devices.get(device_name);
    if (path == null || path.isEmpty())
        throw new Exception("Device " + device_name + " was not found in this channel!");

    Log.d(TAG, "Loading index " + path);

    ByteArrayOutputStream out = new ByteArrayOutputStream(32768);
    try {//  w ww  .  j  a  v a 2  s.c  o m
        if (!Utils.downloadFile(dev.getUbuntuBaseUrl() + path, out, null, true) || out.size() == 0)
            return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    m_images = new TreeMap<Integer, UbuntuImage>();

    Object rawObject = new JSONTokener(out.toString()).nextValue();
    if (!(rawObject instanceof JSONObject)) {
        Log.e(TAG, "Malformed manifest format!");
        return false;
    }

    JSONArray images = ((JSONObject) rawObject).getJSONArray("images");
    for (int i = 0; i < images.length(); ++i) {
        JSONObject img = images.getJSONObject(i);

        // We only need full images because we do only clean install
        if (!img.getString("type").equals("full"))
            continue;

        UbuntuImage uimg = new UbuntuImage(img);
        m_images.put(uimg.version, uimg);
    }
    return true;
}

From source file:m2.android.archetype.example.FacebookSdk.internal.Utility.java

public static Object getStringPropertyAsJSON(JSONObject jsonObject, String key, String nonJSONPropertyKey)
        throws JSONException {
    Object value = jsonObject.opt(key);
    if (value != null && value instanceof String) {
        JSONTokener tokener = new JSONTokener((String) value);
        value = tokener.nextValue();//from   w ww  .java2s.c o m
    }

    if (value != null && !(value instanceof JSONObject || value instanceof JSONArray)) {
        if (nonJSONPropertyKey != null) {
            // Facebook sometimes gives us back a non-JSON value such as
            // literal "true" or "false" as a result.
            // If we got something like that, we present it to the caller as
            // a GraphObject with a single
            // property. We only do this if the caller wants that behavior.
            jsonObject = new JSONObject();
            jsonObject.putOpt(nonJSONPropertyKey, value);
            return jsonObject;
        } else {
            throw new FacebookException("Got an unexpected non-JSON object.");
        }
    }

    return value;

}

From source file:com.appbase.androidquery.callback.AbstractAjaxCallback.java

@SuppressWarnings("unchecked")
protected T transform(String url, byte[] data, AjaxStatus status) {

    if (type == null) {
        return null;
    }//w  ww . j a va2s .  c  o m

    File file = status.getFile();

    if (data != null) {

        if (type.equals(Bitmap.class)) {
            return (T) BitmapFactory.decodeByteArray(data, 0, data.length);
        }

        if (type.equals(JSONObject.class)) {

            JSONObject result = null;
            String str = null;
            try {
                str = new String(data, encoding);
                result = (JSONObject) new JSONTokener(str).nextValue();
            } catch (Exception e) {
                AQUtility.debug(e);
                AQUtility.debug(str);
            }
            return (T) result;
        }

        if (type.equals(JSONArray.class)) {

            JSONArray result = null;

            try {
                String str = new String(data, encoding);
                result = (JSONArray) new JSONTokener(str).nextValue();
            } catch (Exception e) {
                AQUtility.debug(e);
            }
            return (T) result;
        }

        if (type.equals(String.class)) {

            String result = null;

            if (status.getSource() == AjaxStatus.NETWORK) {
                AQUtility.debug("network");
                result = correctEncoding(data, encoding, status);
            } else {
                AQUtility.debug("file");
                try {
                    result = new String(data, encoding);
                } catch (Exception e) {
                    AQUtility.debug(e);
                }
            }

            return (T) result;
        }

        /*
        if(type.equals(XmlDom.class)){
                   
           XmlDom result = null;
                   
           try {    
              result = new XmlDom(data);
           } catch (Exception e) {           
              AQUtility.debug(e);
           }
                   
           return (T) result; 
        }
        */

        if (type.equals(byte[].class)) {
            return (T) data;
        }

        if (transformer != null) {
            return transformer.transform(url, type, encoding, data, status);
        }

        if (st != null) {
            return st.transform(url, type, encoding, data, status);
        }

    } else if (file != null) {

        if (type.equals(File.class)) {
            return (T) file;
        }

        if (type.equals(XmlDom.class)) {

            XmlDom result = null;

            try {
                FileInputStream fis = new FileInputStream(file);
                result = new XmlDom(fis);
                status.closeLater(fis);
            } catch (Exception e) {
                AQUtility.report(e);
                return null;
            }

            return (T) result;
        }

        if (type.equals(XmlPullParser.class)) {

            XmlPullParser parser = Xml.newPullParser();
            try {

                FileInputStream fis = new FileInputStream(file);
                parser.setInput(fis, encoding);
                status.closeLater(fis);
            } catch (Exception e) {
                AQUtility.report(e);
                return null;
            }
            return (T) parser;
        }

        if (type.equals(InputStream.class)) {
            try {
                FileInputStream fis = new FileInputStream(file);
                status.closeLater(fis);
                return (T) fis;
            } catch (Exception e) {
                AQUtility.report(e);
                return null;
            }
        }

    }

    return null;
}

From source file:com.gmail.tylerfilla.axon.ui.activity.HelpFOSSViewerActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Inflate and set content view
    setContentView(R.layout.activity_help_foss_viewer);

    // Find stuff
    Toolbar appBar = (Toolbar) findViewById(R.id.activity_help_foss_viewer_app_bar);
    WebView browser = (WebView) findViewById(R.id.activity_help_foss_viewer_browser);

    // Configure app bar
    setSupportActionBar(appBar);//from w ww.  ja  va  2  s.  co  m

    // Display up button in app bar
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Apply dark tint to navigation icon
    // noinspection ConstantConditions
    Drawable navigationIcon = DrawableCompat.wrap(appBar.getNavigationIcon());
    DrawableCompat.setTint(navigationIcon, 0x8b000000);
    appBar.setNavigationIcon(navigationIcon);

    // Get component index which was passed in
    int componentIndex = getIntent().getIntExtra("componentIndex", -1);

    if (componentIndex != -1) {
        // Component information
        String componentName = "";
        String licenseName = "";
        String licenseTextURL = "";

        try {
            // Read components file into a buffer
            StringWriter componentFileBuffer = new StringWriter();
            IOUtils.copy(getAssets().open("foss/components.json"), componentFileBuffer,
                    Charset.defaultCharset());

            // Parse component object from file
            JSONObject component = ((JSONArray) new JSONTokener(componentFileBuffer.toString()).nextValue())
                    .getJSONObject(componentIndex);

            // Extract component information from its JSON object
            componentName = component.getString("name");
            licenseName = component.getString("licenseName");
            licenseTextURL = component.getString("licenseTextURL");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // Set title and subtitle
        setTitle(componentName);
        appBar.setSubtitle(licenseName);

        // Load license URL
        browser.loadUrl(licenseTextURL);
    }
}

From source file:org.picketbox.test.json.JSONSecurityTestCase.java

@Test
public void parseJSONWebKey() throws Exception {
    URL url = getClass().getClassLoader().getResource("json/jsonWebKey.json");
    assertNotNull(url);//from  w w  w. ja va  2  s  .  c  o m
    File file = new File(url.toURI());

    FileReader reader = new FileReader(file);
    JSONTokener tokener = new JSONTokener(reader);
    JSONObject json = new JSONObject(tokener);
    assertNotNull(json);
    System.out.println(json.toString());

    JSONWebKey webKey = new JSONWebKey();
    webKey.parse(json);
    assertEquals(2, webKey.getKeys().length());
    JSONObject keyObj = webKey.getKey("2011-04-29");
    RSAKey rsa = new RSAKey();
    rsa.parse(keyObj);

    RSAPublicKey publicKey = rsa.convertToPublicKey();
    assertNotNull(publicKey);

    RSAKey convertedKey = RSAKey.convert(publicKey);
    assertNotNull(convertedKey);
}

From source file:com.nicolacimmino.expensestracker.tracker.expenses_api.ExpensesApiRequest.java

public boolean performRequest() {

    jsonResponseArray = null;/*from ww w  . j  a  v  a2 s  . c om*/
    jsonResponseObject = null;

    HttpURLConnection connection = null;

    try {

        // Get the request JSON document as U*TF-8 encoded bytes, suitable for HTTP.
        mRequestData = ((mRequestData != null) ? mRequestData : new JSONObject());
        byte[] postDataBytes = mRequestData.toString(0).getBytes("UTF-8");

        URL url = new URL(mUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(mRequestMethod == "GET" ? false : true); // No body data for GET
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod(mRequestMethod);
        connection.setUseCaches(false);

        // For all methods except GET we need to include data in the body.
        if (mRequestMethod != "GET") {
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("charset", "utf-8");
            connection.setRequestProperty("Content-Length", "" + Integer.toString(postDataBytes.length));

            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.write(postDataBytes);
            wr.flush();
            wr.close();
        }

        if (connection.getResponseCode() == 200) {
            InputStreamReader in = new InputStreamReader((InputStream) connection.getContent());
            BufferedReader buff = new BufferedReader(in);
            String line = buff.readLine().toString();
            buff.close();
            Object json = new JSONTokener(line).nextValue();
            if (json.getClass() == JSONObject.class) {
                jsonResponseObject = (JSONObject) json;
            } else if (json.getClass() == JSONArray.class) {
                jsonResponseArray = (JSONArray) json;
            } // else members will be left to null indicating no valid response.
            return true;
        }

    } catch (MalformedURLException e) {
        Log.e(TAG, e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
    } catch (JSONException e) {
        Log.e(TAG, e.getMessage());
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

    return false;
}