Java escape JSON String?

前端 未结 10 630
再見小時候
再見小時候 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: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;
    }
    

提交回复
热议问题