Menu

Problem serializing a HTML string.

Help
2008-07-24
2013-04-29
  • Jose Monzon

    Jose Monzon - 2008-07-24

    Hello everybody!

    I'm getting an extrange behaviour when serializing strings using this JSON library. The best is to ilustrate it with a example. Let's consider the following JUNIT test:

    import net.sf.json.JSONArray;
    import net.sf.json.JSONObject;
    import net.sf.json.JSONString;
    import net.sf.json.JsonConfig;

    import org.junit.Test;

    public class JsonTest {
        @Test
        public void testHTMLConversion(){
            JSONArray obj = JSONArray.fromObject( new String[]{"<b>as</b>"});
            System.out.println(obj.toString());
        }
    }

    If I run that test the exit is: "["<b>as<\/b>"]"  Please, notice the slash escape.

    If instead of "<b>as</b>" I run the test with: "<b>as< /b>" (notice the space between < and  /, the result is not escaped: ["<b>as< /b>"]

    I'm getting problems in my client software because this library is scaping strings that contains "</" and I don't know what to do to prevent it. Why is this happening???

    Thanks

     
    • aalmiray

      aalmiray - 2008-07-24

      Jose,

      The answer lies in JSONUtils.quote, per the javadoc

      /**
      * Produce a string in double quotes with backslash sequences in all the
      * right places. A backslash will be inserted within </, allowing JSON text
      * to be delivered in HTML. In JSON text, a string cannot contain a control
      * character or an unescaped quote or backslash.<br>
      * <strong>CAUTION:</strong> if <code>string</code> represents a
      * javascript function, translation of characters will not take place. This
      * will produce a non-conformant JSON text.
      *
      * @param string A String
      * @return A String correctly formatted for insertion in a JSON text.
      */

      This is why '</' is escaped but '< /' is not. Given that some users may rely on this to be the default case, we may add configuration flag to JsonConfig to skip escaping '</', how about that?

      Cheers,
      Andres

       
    • Jose Monzon

      Jose Monzon - 2008-07-25

      Oh, thanks for the answer. It could be great to add that configuration flag.

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.