Remove all occurrences of \ from string

后端 未结 6 1243
挽巷
挽巷 2020-12-03 03:12

I am trying to get an array of objects from the server, using JSON.

The server sends me the following string.

\"[{\\\"DealComment\\\":null,\\\"DealVo         


        
相关标签:
6条回答
  • 2020-12-03 03:31

    Try this:

    String jsonFormattedString = jsonStr.replaceAll("\\\\", "");
    

    Because the backslash is the escaping character in a regular expression (replaceAll() receives one as parameter), it has to be escaped, too.

    0 讨论(0)
  • 2020-12-03 03:31

    You can just use:

    str.replace("\\","");
    

    replace takes string as param, replaceAll uses RegEx. it may work like this also:

    str.replaceAll("\\\\", "");
    
    0 讨论(0)
  • 2020-12-03 03:32
    jsonObj.toString()
            .replace("\"[", "[").replace("]\"", "]")
            .replace("\\\"{", "{").replace("}\\\"", "}")
            .replace("\\\\\\\"", "\"")
    
    0 讨论(0)
  • 2020-12-03 03:35

    It looks like your incoming string is doubly JSON encoded. You should decode it, then decode that again.

    Here's my best guess as to how you might do that in Java:

    JSONArray resultArray = new JSONArray(new JSONString(jsonFormattedString));
    

    I'm assuming here that JSONString is a type. Your actual solution may vary.

    Under normal circumstances, I'd expect a service to give you JSON straight up. It appears that this services is giving you a string (encoded according to the JSON spec) which contains JSON.

    It's the difference between the following:

    String someJSON = "[0, 1, 2]";
    String doublyEncodedJSON = "\"[0, 1, 2]\"";
    

    Notice the extra leading and trailing quotes? That's because the latter is a string of JSON. You'd have to decode it twice to get the actual object.

    0 讨论(0)
  • 2020-12-03 03:38

    Actually the correct way would be:

    String jsonFormattedString = jsonStr.replace("\\\"", "\"");
    

    You want to replace only \" with ", not all \ with nothing (it would eat up your slashes in json strings, if you have ones). Contrary to popular believe replace(...) also replaces all occurrences of given string, just like replaceAll(...), it just doesn't use regexp so it usually be faster.

    0 讨论(0)
  • 2020-12-03 03:50

    Just use:

    try {
            jsonFormattedString = new JSONTokener(jsonString).nextValue().toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    

    See documentation

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