0

All json values should be encoded.

new JSONObject().put("JSON", "csds\"").toString();

should return

csds%22

not

csds"

Above is just a small example to explain the problem.

In actual the JSON data will be very large. So I don't want to encode each value using URLencoder. I am looking for some configuration which will always encode the JSON values in the returned JSON string.

Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43
Dixit Singla
  • 2,540
  • 3
  • 24
  • 39

2 Answers2

0

this should work:

URLEncoder.encode("csds\"", "UTF-8")
Khalil M
  • 1,788
  • 2
  • 22
  • 36
  • JSON will be very large. I have updated the question. please have a look – Dixit Singla Sep 21 '17 at 13:58
  • @DixitSingla what are trying to achieve? because with URLencoder or anything else that will encode, the Json will be as large as same as with any other method – Khalil M Sep 21 '17 at 14:40
0

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();
}
Leo Aso
  • 11,898
  • 3
  • 25
  • 46