Java escape JSON String?

前端 未结 10 628
再見小時候
再見小時候 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 11:42

    Consider Moshi's JsonWriter class (source). It has a wonderful API and it reduces copying to a minimum, everything is nicely streamed to the OutputStream.

    OutputStream os = ...;
    JsonWriter json = new JsonWriter(Okio.sink(os));
    json
      .beginObject()
      .name("id").value(userID)
      .name("type").value(methodn)
      ...
      .endObject();
    
    0 讨论(0)
  • 2020-12-08 11:43

    If you want to simply escape a string, not an object or array, use this:

    String escaped = JSONObject.valueToString(" Quotes \" ' ' \" ");
    

    http://www.json.org/javadoc/org/json/JSONObject.html#valueToString(java.lang.Object)

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-08 11:51

    According to the answer here, quotes in values need to be escaped. You can do that with \"

    So just repalce the quote in your values

    msget = msget.replace("\"", "\\\"");
    
    0 讨论(0)
  • 2020-12-08 11:52

    The best method would be using some JSON library, e.g. Jackson ( http://jackson.codehaus.org ).

    But if this is not an option simply escape msget before adding it to your string:

    The wrong way to do this is

    String msgetEscaped = msget.replaceAll("\"", "\\\"");
    

    Either use (as recommended in the comments)

    String msgetEscaped = msget.replace("\"", "\\\"");
    

    or

    String msgetEscaped = msget.replaceAll("\"", "\\\\\"");
    

    A sample with all three variants can be found here: http://ideone.com/Nt1XzO

    0 讨论(0)
  • 2020-12-08 11:56

    Try to replace all the " and ' with a \ before them. Do this just for the msget object(String, I guess). Don't forget that \ must be escaped too.

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