public JSONObject getJSONObject(String key) throws JSONException { JSONValue v = get(key); if (v == null) throw new JSONException(JSONErrorCode.KeyIsNotFound, key); JSONObject o = v.getJSONObject(); if (o == null) throw new JSONException(JSONErrorCode.NotAJSONObject, v.toString()); return o; }
public String getString(String key) throws JSONException { JSONValue v = get(key); if (v == null) throw new JSONException(JSONErrorCode.KeyIsNotFound, key); JSONString s = v.getJSONString(); if (s == null) throw new JSONException(JSONErrorCode.NotAJSONString, v.toString()); return s.getValue(); }
public int getInt(String key) throws JSONException { JSONValue v = get(key); if (v == null) throw new JSONException(JSONErrorCode.KeyIsNotFound, key); JSONNumber n = v.getJSONNumber(); if (n == null) throw new JSONException(JSONErrorCode.NotAJSONNumber, v.toString()); return n.getIntValue(); }
// This method assumes that the JSON value being passed is a JSON // non-primitive: // either an object or an array. // This helps to make this implementation as efficient as possible. protected String jsonNonPrimitiveToPrettyString(JSONValue jsonValue, int indentLevel) { StringBuffer buffer = new StringBuffer(); // If the value in question is an object JSONObject jsonValueObject = jsonValue.isObject(); if (jsonValueObject != null) { boolean firstKey = true; for (String key : jsonValueObject.keySet()) { if (firstKey) { firstKey = false; } else { buffer.append(",\n"); } for (int k = 0; k < indentLevel; ++k) { buffer.append(" "); } buffer.append(key).append(" : "); JSONValue jsonObjectValue = jsonValueObject.get(key); if (jsonObjectValue != null) { if (jsonObjectValue.isObject() != null) { buffer .append("{\n") .append(jsonNonPrimitiveToPrettyString(jsonObjectValue, indentLevel + 1)) .append("}"); } else if (jsonObjectValue.isArray() != null) { buffer .append("[\n") .append(jsonNonPrimitiveToPrettyString(jsonObjectValue, indentLevel + 1)) .append("]"); } else { // If the object value is a primitive, just prints it, // there is no need for a recursive call! buffer.append(jsonObjectValue.toString()); } } } } else if (jsonValue.isArray() != null) { // If the value in question is an array JSONArray jsonValueArray = jsonValue.isArray(); for (int i = 0; i < jsonValueArray.size(); ++i) { if (0 < i) { buffer.append(",\n"); } for (int k = 0; k < indentLevel; ++k) { buffer.append(" "); } JSONValue jsonArrayValue = jsonValueArray.get(i); if (jsonArrayValue != null) { if (jsonArrayValue.isObject() != null) { buffer .append("{\n") .append(jsonNonPrimitiveToPrettyString(jsonArrayValue, indentLevel + 1)) .append("}"); } else if (jsonArrayValue.isArray() != null) { buffer .append("[\n") .append(jsonNonPrimitiveToPrettyString(jsonArrayValue, indentLevel + 1)) .append("]"); } else { // If the object value is a primitive, just prints it, // there is no need for a recursive call! buffer.append(jsonArrayValue.toString()); } } } } return buffer.toString(); }