如何将含转义符、换行符的字符串转为纯字符串并生成JSONObject
Hey there! Let's work through this problem together. You want to turn that formatted, newline-filled string into a compact JSON string (and eventually a JSONObject) without using regex—totally doable. Here are two straightforward methods:
Method 1: Pure String Manipulation (No Regex)
Since your string contains literal \n characters (the newlines you see in output), we can use basic String.replace() (which replaces all literal matches, no regex needed) to clean things up:
String str = "[{\\n \"country_group\": [\"Asia\"],\\n \"country\": [\\n \"IND\" , \"China\"\\n ]\\n },\\n {\\n \"country_group\": [\"NAmerica\"],\\n \"country\": [\\n \"US\"\\n ]\\n }]"; // Step 1: Remove all newline characters String compactStr = str.replace("\n", ""); // Step 2: Clean up extra consecutive spaces (since removing newlines might leave doubles) while (compactStr.contains(" ")) { compactStr = compactStr.replace(" ", " "); } // Print the compact string (matches your desired output) System.out.println(compactStr); // Convert to JSONObject (note: your input is a JSON array, so we'll use JSONArray first) JSONArray jsonArray = new JSONArray(compactStr); // If you need a wrapping JSONObject: JSONObject jsonObject = new JSONObject(); jsonObject.put("countryList", jsonArray);
Note: We use String.replace() (not replaceAll()) because it works with literal strings, not regular expressions—perfect for your requirement.
Method 2: Direct JSON Parsing (Recommended, No Manual String Tweaks)
The best approach is to skip manual string cleaning entirely. JSON parsers (like org.json, Jackson, or Gson) automatically ignore whitespace (newlines, spaces, tabs) in valid JSON. This is more reliable because it avoids accidental damage to actual string content (e.g., if a country name had a newline in it, manual replacement would break it).
Using org.json as an example:
import org.json.JSONArray; import org.json.JSONObject; String str = "[{\\n \"country_group\": [\"Asia\"],\\n \"country\": [\\n \"IND\" , \"China\"\\n ]\\n },\\n {\\n \"country_group\": [\"NAmerica\"],\\n \"country\": [\\n \"US\"\\n ]\\n }]"; // Directly parse the original string into a JSONArray (since your input is an array) JSONArray jsonArray = new JSONArray(str); // To get the compact JSON string you want, just call toString() System.out.println(jsonArray.toString()); // Convert to a JSONObject if needed (e.g., wrap the array in a key-value pair) JSONObject jsonObject = new JSONObject(); jsonObject.put("countries", jsonArray);
This method is cleaner, safer, and still avoids regex entirely—win-win!
内容的提问来源于stack exchange,提问作者saurabh gupta

