[Stripes-users] content escaping in JSONBuilder

Subject:   [Stripes-users] content escaping in JSONBuilder (find more)
From:   Sergey Pariev <hidden> (find more)
Date:   Jan 19, 2006 06:17

Hi all.

I noticed some errors while using JSONBuilder recently - namely it
doesn't escape string values which results in errors thet trying to
eval() it on the JavaScript side. The following is the changes I've
made to JSONBuilder to eliminate that issue :

- new method added , quote() :

public static String quote(String string) {
 if (string == null || string.length() == 0) {
  return "\"\"";
 }
 char         b;
         char         c = 0;
 int          i;
 int          len = string.length();
 StringBuffer sb = new StringBuffer(len + 4);
 String       t;

 sb.append('"');
 for (i = 0; i < len; i += 1) {
  b = c;
  c = string.charAt(i);
  switch (c) {
   case '\\':
   case '"':
    sb.append('\\');
    sb.append(c);
    break;
   case '/':
    if (b == '<') {
     sb.append('\\');
    }
           sb.append(c);
    break;
   case '\b':
    sb.append("\\b");
    break;
   case '\t':
    sb.append("\\t");
    break;
   case '\n':
    sb.append("\\n");
    break;
   case '\f':
    sb.append("\\f");
    break;
   case '\r':
    sb.append("\\r");
    break;
   default:
    if (c < ' ') {
    t = "000" + Integer.toHexString(c);
    sb.append("\\u" + t.substring(t.length() - 4));
    } else {
     sb.append(c);
    }
   }
 }
 sb.append('"');
 return sb.toString();
}

  
- method getScalarAsString was changed as follows :

public String getScalarAsString(Object in) {
 Class type = in.getClass();
 String result = null;
         if (String.class.isAssignableFrom(type)) {
  result =  quote((String)in) ;
 }
 else if(Date.class.isAssignableFrom(type)) {
  result = "new Date(" + ((Date) in).getTime() + ")";
  }
 else {
  result = in.toString();
 }   
  
 return result ;
}


HTH, Sergey.


-------------------------------------------------------
This SF.net email is sponsored by: Splunk Inc. Do you grep through log files
for problems?  Stop!  Download the new AJAX search engine that makes
searching your log files as easy as surfing the  web.  DOWNLOAD SPLUNK!
http://sel.as-us.falkag.net/sel?cmd=lnk&kid=103432&bid=230486&dat=121642
_______________________________________________
Stripes-users mailing list
hidden
https://lists.sourceforge.net/lists/listinfo/stripes-users
Entire Thread (Showing 2 of 2)