Parsing error: A quick solution to rich text json string of with double quotation marks

  • 2021-11-02 02:03:31
  • OfStack

The project of the company, which is sent back through json, is this thing:


NewsId":"94f52614-8764-46d7-a5fe-d0da1fe878ed","NewsTitle":" Series of Large-scale Public Elective Courses "Sustainable Development and Future" 2 The modern economy (green economy) began to register for online courses ","NewsContent":"<span style="font-size:12pt;font-family: Song Style ;color:black;line-height:150%;"><span> Recently, along with Academician Zheng Shiling and Professor Tong Xiaohua of our school, 4 The wonderful speeches held in Ping and Jiading, and the series of large-scale public elective courses "Sustainable Development and the Future" created by our school this semester 1 Has been successfully concluded. This course is also our school </span> " <span> Minor major in sustainable development </span> " <span> One of the core compulsory courses of 1 . </span></span> 
<p style="text-indent:21pt;">
</p>.........
</span>

After various queries, it is found that the root cause of unparsed is that there are double quotation marks "" "and backslashes"\ ".

You can't escape json directly, otherwise you will escape the double quotation marks of json itself, so you can't escape it violently

How to find it online:


// Will be bad json The double quotation marks in the data are changed to the double quotation marks in Chinese ( Anything, as long as it's not double quotation marks )
	public String jsonStringConvert(String s){
    		char[] temp = s.toCharArray();    
    		int n = temp.length;
    		for(int i =0;i<n;i++){
      	if(temp[i]==':'&&temp[i+1]=='"'){
          for(int j =i+2;j<n;j++){
            if(temp[j]=='"'){
              if(temp[j+1]!=',' && temp[j+1]!='}'){
                temp[j]=' " ';
              }else if(temp[j+1]==',' || temp[j+1]=='}'){
                break ;
              }
            }
          }  
      	}
    }    
    return new String(temp);
  }</span>

This method can escape double quotation marks other than the double quotation marks of json itself to Chinese double quotation marks (anything else will do). This can escape to the correct json string.

Memo:

Before this method, the html code should be blanketed, otherwise json can not be parsed, and the blanketed method:


public String replaceBlank(String str) {
		String dest = "";
	if (str != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
		Matcher m = p.matcher(str);
			dest = m.replaceAll("");
			// Pattern p2 = Pattern.compile("\\s*\"");
			// Matcher m2 = p2.matcher(dest);
			// dest = m2.replaceAll("\'");
			dest = dest.replace("=\"", "='");
			p = Pattern.compile("\"\0*>");
			m = p.matcher(dest);
			dest = m.replaceAll(">'");
		}
		return dest;
}</span>

Related articles: