逃离杰克逊的斜线

时间:2011-07-25 14:16:32

标签: java json escaping jackson

我使用Jackson生成JSON对象并将它们直接写入HTML的标记中,如下所示:

   <script>
     var data = $SomeJacksonWrapper.toJson($data);
   </script>

如果某个字符串中包含'</script>',则此代码会中断。转义正斜杠(/)可以解决问题,并且它是由JSON的规范赋予的。

如何在杰克逊中启用它?

3 个答案:

答案 0 :(得分:9)

使用 StaxMan 的回答,我最终得到了以下代码:

   public class CustomCharacterEscapes extends CharacterEscapes {

     private static final Logger log = Logger.getLogger(CustomCharacterEscapes.class);

     private final int[] _asciiEscapes;

     public CustomCharacterEscapes() {
       _asciiEscapes = standardAsciiEscapesForJSON();
       _asciiEscapes['/'] = CharacterEscapes.ESCAPE_STANDARD;
     }

     @Override
     public int[] getEscapeCodesForAscii() {
       return _asciiEscapes;
     }

     @Override
     public SerializableString getEscapeSequence(int i) {
       return null;
    }
  }


    public class CustomObjectMapper extends ObjectMapper {

     public CustomObjectMapper() {
       this.getJsonFactory().setCharacterEscapes(new CustomCharacterEscapes());
     }

    }

答案 1 :(得分:8)

除了其他建议外,Jackson 1.8还具有“character escapes”功能,可以重新定义转义规则。缺少文档,但基本上你需要实现CharacterEscapes(参见http://jackson.codehaus.org/1.8.2/javadoc/org/codehaus/jackson/io/CharacterEscape),注册JsonFactory(或直接注册JsonGenerator),然后根据你想要的规则进行转义。在这种情况下,您只需更改“/”的设置即可使用ESCAPE_STANDARD。

此外,您还可以添加功能请求以添加简单的开/关功能,因为这个特定的事情听起来也可能对其他人有用。但据我所知,尚未特别要求。

答案 2 :(得分:7)

感谢StaxMan和Infeligo的答案(欢呼伙伴)我找到了一种方法来提供/匹配(恕我直言)可怕的WCF DataContractJsonSerializer日期标准格式:

/Date(1328053610008+1100)/

需要使用反斜杠进行转义,从而导致以下内容:

\/Date(1328053610008+1100)\/

以防万一我可以帮助其他人使用我的CustomCharacterEscapes代码:

public class CustomCharacterEscapes extends CharacterEscapes {

    private final int[] _asciiEscapes;

    public CustomCharacterEscapes() {
        _asciiEscapes = standardAsciiEscapesForJSON();
        _asciiEscapes['/'] = CharacterEscapes.ESCAPE_CUSTOM;
    }

    @Override
    public int[] getEscapeCodesForAscii() {
        return _asciiEscapes;
    }

    @Override
    public SerializableString getEscapeSequence(int i) {
        if(i == '/'){
            return new SerializableString() {

                @Override
                public String getValue() {
                    return "\\/";
                }

                @Override
                public int charLength() {
                    return 2;
                }

                @Override
                public char[] asQuotedChars() {
                    return new char[]{'\\','/'};
                }

                @Override
                public byte[] asUnquotedUTF8() {
                    return new byte[]{'\\','/'};
                }

                @Override
                public byte[] asQuotedUTF8() {
                    return new byte[]{'\\','/'};
                }
            };
        }
        else{
            return null;
        }
    }
}