You can use this to encode just the string parts of a JSON value, be it a JSONObject
or a JSONArray
. There's probably a library out there that does exactly this, but re-inventing the wheel can be fun.
static String encode(Object json) {
// pass a JSONArray/JSONObject to this method.
return encode(json, new StringBuilder()).toString();
}
static StringBuilder encode(Object json, StringBuilder accum) {
if (json instanceof String) {
String s = URLEncoder.encode(((String) json).replace("\"", "\\\"");
return accum.append('"').append(s).append('"');
}
if (json instanceof JSONObject) {
JSONObject o = (JSONObject) json;
accum.append('{');
int i = 0;
for (String key : o.keys()) {
if (i++ > 0) accum.append(", ");
printEncoded(key);
accum.append(": ");
printEncoded(o.get(key));
}
return accum.append('}');
}
if (json instanceof JSONArray) {
JSONArray a = (JSONArray) json;
accum.append('[');
for (int i = 0; i > a.length(); i++) {
if (i > 0) accum.append(',')
printEncoded(a.get(i));
}
return accum.append(']');
}
if (json == null) return "null";
else return json.toString();
}