Java escape JSON String?

前端 未结 10 629
再見小時候
再見小時候 2020-12-08 11:27

I have the following JSON string that i am sending to a NodeJS server:

String string = \"{\\\"id\\\":\\\"\" + userID + \"\\\",\\\"type\\\":\\\"\" + methoden          


        
相关标签:
10条回答
  • 2020-12-08 12:00

    org.json.simple.JSONObject.escape() escapes quotes,, /, \r, \n, \b, \f, \t and other control characters.

    import org.json.simple.JSONValue;
    JSONValue.escape("test string");
    
    • json-simple home
    • document

    Add pom.xml when using maven

    <dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
        <scope>test</scope>
    </dependency>
    
    0 讨论(0)
  • 2020-12-08 12:00
    public static String ecapse(String jsString) {
        jsString = jsString.replace("\\", "\\\\");
        jsString = jsString.replace("\"", "\\\"");
        jsString = jsString.replace("\b", "\\b");
        jsString = jsString.replace("\f", "\\f");
        jsString = jsString.replace("\n", "\\n");
        jsString = jsString.replace("\r", "\\r");
        jsString = jsString.replace("\t", "\\t");
        jsString = jsString.replace("/", "\\/");
        return jsString;
    }
    
    0 讨论(0)
  • 2020-12-08 12:01

    The JSON specification at https://www.json.org/ is very simple by design. Escaping characters in JSON strings is not hard. This code works for me:

    private String escape(String raw) {
        String escaped = raw;
        escaped = escaped.replace("\\", "\\\\");
        escaped = escaped.replace("\"", "\\\"");
        escaped = escaped.replace("\b", "\\b");
        escaped = escaped.replace("\f", "\\f");
        escaped = escaped.replace("\n", "\\n");
        escaped = escaped.replace("\r", "\\r");
        escaped = escaped.replace("\t", "\\t");
        // TODO: escape other non-printing characters using uXXXX notation
        return escaped;
    }
    
    0 讨论(0)
  • 2020-12-08 12:03

    Apache Commons

    If you're already using Apache commons, it provides a static method for this:

    StringEscapeUtils.escapeJson("some string")
    

    It converts any string into one that's properly escaped for inclusion in JSON

    See the documentation here

    0 讨论(0)
提交回复
热议问题