Java escape JSON String?

前端 未结 10 654
再見小時候
再見小時候 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 11:47

    I would use a library to create your JSON String for you. Some options are:

    • GSON
    • Crockford's lib

    This will make dealing with escaping much easier. An example (using org.json) would be:

    JSONObject obj = new JSONObject();
    
    obj.put("id", userID);
    obj.put("type", methoden);
    obj.put("msg", msget);
    
    // etc.
    
    final String json = obj.toString(); // <-- JSON string
    

提交回复
热议问题