2016-04-11 49 views
1

我正在編寫一個將JSON文件寫入CodeMirror窗口的硒測試。這是我的代碼到目前爲止:Selenium - 使用換行符將文件寫入codemirror

public void setJson(String jsonPath) throws IOException, InterruptedException { 

    // Read a file to a string 
    byte[] encoded = Files.readAllBytes(Paths.get(jsonPath)); 
    String jsonText = new String(encoded, StandardCharsets.UTF_8); 

    // Get rid of line breaks 
    jsonText = jsonText.replace("\n", ""); 
    // Escape the quotes 
    jsonText = jsonText.replace("\"", "\\\""); 

    // Write to the CodeMirror 
    WebElement queryInput = driver.findElement(By.xpath("//*[@id=\"content\"]/div/div[2]/div/div[1]/div[1]/div/div/div/div")); 
    JavascriptExecutor js = (JavascriptExecutor) driver; 
    js.executeScript("arguments[0].CodeMirror.setValue(\"" + jsonText + "\");", queryInput); 

} 

此代碼的工作原理。但它將整個JSON文件寫入一行。這是我嘗試的一些事情。

  1. 不替代「\ n」。這給出了「未終止的字符串文字」錯誤
  2. 用「\ r」替換「\ n」。同樣的錯誤。
  3. 將「\ n」替換爲「< \ br>」(沒有反斜槓,我甚至無法在堆棧溢出時進行換行符)。這只是把一堆「br」標籤放在json文本中。

任何想法?我猜測有一種方法可以逐行執行此操作,但我寧願能夠將整個文件作爲一個字符串發送。

+0

什麼是你的JSON?它是否有換行符,或者您是否在尋找漂亮的打印機? –

+0

請粘貼您的JSON以便我們可以更好地幫助您。另外一個瘋狂的猜測在這裏..嘗試替換「\ n」使用「\\ n」 – Vedanshu

+0

JSON有換行符(「\ n」),但是如果我把它們留在那裏,我得到了「未終止的字符串文字」錯誤。我用「\\ n」取代了它們,一切正常!謝謝Vedanshu! – user2014969

回答

0

爲了擺脫線的突破

嘗試:

jsonText = jsonText.replaceAll("\n", "\\\\\\\\\\\\\\\\r\\\\\\\\\\\\\\\\n"); // for all occurrence 
// This will replace \n with \\\\r\\\\n a new line for codemirror 

jsonText = jsonText.replace("\n", "\\\\\\\\\\\\\\\\r\\\\\\\\\\\\\\\\n"); 
相關問題