Я пишу простую java-программу для чтения JSON-файла и извлечения из него определенной информации. Однако функция разделения String не разделяет строку на new line
ИЛИ \n
символ.java - невозможно разбить строку на новой строке из JSON
Ниже мой JSON файл - sample.json
{
"seleniumLog": [
{
"commandName": "sendKeys",
"args": [
"[[\"testUSER\",\"xpath\\u003d//UIAApplication[1]/UIAWindow[2]/UIATextField[1]\"]]"
],
"result": "fail",
"subLogs": [
{
"commandName": "getCurrentWindowHandle",
"args": [
"{}"
],
"result": "Not implemented in this context, try switching into or out of a web view (WARNING: The server did not provide any stacktrace information)\nCommand duration or timeout: 6 milliseconds\nBuild info: version: '2.39.0', revision: 'ff23eac', time: '2013-12-16 16:11:15'\nSystem info: host: 'testUSER-SIRs-MacBook-Pro.local', ip: '127.0.0.1', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.8.5', java.version: '1.6.0_65'\nSession ID: aced75a4-2bd9-4147-8346-1973371d2f97\nDriver info: com.infostretch.automation.ui.webdriver.QAFExtendedWebDriver\nCapabilities [{platform=MAC, app=/Users/testUSER/IAirwaysPG.app, javascriptEnabled=true, browserName=, desired={\"app\":\"/Users/testUSER/IAirwaysPG.app\",\"platformVersion\":\"7.1\",\"deviceName\":\"iPhone Simulator\",\"platformName\":\"iOS\",\"browserName\":\"\"}, locationContextEnabled=false, version=, platformVersion=7.1, databaseEnabled=false, cssSelectorsEnabled=true, platformName=ios, deviceName=iPhone Simulator, browser_name=, webStorageEnabled=false, warnings={}, takesScreenshot=true}]",
"subLogs": []
}
]
}
],
"checkPoints": [
{
"message": "Browser: ",
"type": "Info",
"screenshot": "",
"subCheckPoints": []
},
{
"message": "sendKeys [\"testUSER\",\"xpath\\u003d//UIAApplication[1]/UIAWindow[2]/UIATextField[1]\"] into {1}",
"type": "TestStepFail",
"subCheckPoints": [
{
"message": "Not implemented in this context, try switching into or out of a web view (WARNING: The server did not provide any stacktrace information)\nCommand duration or timeout: 6 milliseconds\nBuild info: version: '2.39.0', revision: 'ff23eac', time: '2013-12-16 16:11:15'\nSystem info: host: 'testUSER-SIRs-MacBook-Pro.local', ip: '127.0.0.1', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.8.5', java.version: '1.6.0_65'\nSession ID: aced75a4-2bd9-4147-8346-1973371d2f97\nDriver info: com.infostretch.automation.ui.webdriver.QAFExtendedWebDriver\nCapabilities [{platform=MAC, app=/Users/testUSER/IAirwaysPG.app, javascriptEnabled=true, browserName=, desired={\"app\":\"/Users/testUSER/IAirwaysPG.app\",\"platformVersion\":\"7.1\",\"deviceName\":\"iPhone Simulator\",\"platformName\":\"iOS\",\"browserName\":\"\"}, locationContextEnabled=false, version=, platformVersion=7.1, databaseEnabled=false, cssSelectorsEnabled=true, platformName=ios, deviceName=iPhone Simulator, browser_name=, webStorageEnabled=false, warnings={}, takesScreenshot=true}]",
"type": "Fail",
"screenshot": "",
"subCheckPoints": []
}
]
}
],
"errorTrace": "org.openqa.selenium.WebDriverException: Not implemented in this context, try switching into or out of a web view (WARNING: The server did not provide any stacktrace information)\nCommand duration or timeout: 6 milliseconds\nBuild info: version: '2.39.0', revision: 'ff23eac', time: '2013-12-16 16:11:15'\nSystem info: host: 'testUSER-SIRs-MacBook-Pro.local', ip: '127.0.0.1', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.8.5', java.version: '1.6.0_65'\nSession ID: aced75a4-2bd9-4147-8346-1973371d2f97\nDriver info: com.infostretch.automation.ui.webdriver.QAFExtendedWebDriver\nCapabilities [{platform=MAC, app=/Users/testUSER/IAirwaysPG.app, javascriptEnabled=true, browserName=, desired={\"app\":\"/Users/testUSER/IAirwaysPG.app\",\"platformVersion\":\"7.1\",\"deviceName\":\"iPhone Simulator\",\"platformName\":\"iOS\",\"browserName\":\"\"}, locationContextEnabled=false, version=, platformVersion=7.1, databaseEnabled=false, cssSelectorsEnabled=true, platformName=ios, deviceName=iPhone Simulator, browser_name=, webStorageEnabled=false, warnings={}, takesScreenshot=true}]\n\tat sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)\n\tat sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)\n\tat sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)\n\tat java.lang.reflect.Constructor.newInstance(Constructor.java:513)\n\tat org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:193)\n\tat org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145)\n\tat org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:554)\n\tat com.infostretch.automation.ui.webdriver.QAFExtendedWebDriver.execute(QAFExtendedWebDriver.java:199)\n\tat org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:569)\n\tat com.infostretch.automation.ui.webdriver.QAFExtendedWebDriver.execute(QAFExtendedWebDriver.java:188)\n\tat org.openqa.selenium.remote.RemoteWebDriver.getWindowHandle(RemoteWebDriver.java:444)\n\tat org.openqa.selenium.internal.seleniumemulation.Windows.<init>(Windows.java:38)\n\tat org.openqa.selenium.WebDriverCommandProcessor.setUpMethodMap(WebDriverCommandProcessor.java:190)\n\tat org.openqa.selenium.WebDriverCommandProcessor.<init>(WebDriverCommandProcessor.java:51)\n\tat com.infostretch.automation.ui.selenium.webdriver.QAFWebDriverCommandProcessor.<init>(QAFWebDriverCommandProcessor.java:53)\n\tat com.infostretch.automation.ui.UiDriverFactory.get(UiDriverFactory.java:74)\n\tat com.infostretch.automation.core.QAFTestBase.init(QAFTestBase.java:187)\n\tat com.infostretch.automation.core.QAFTestBase.getUiDriver(QAFTestBase.java:229)\n\tat com.infostretch.automation.ui.WebDriverTestBase.getDriver(WebDriverTestBase.java:40)\n\tat com.infostretch.automation.ui.webdriver.QAFExtendedWebElement.<init>(QAFExtendedWebElement.java:103)\n\tat com.infostretch.automation.ui.webdriver.QAFExtendedWebElement.<init>(QAFExtendedWebElement.java:114)\n\tat com.infostretch.automation.step.CommonStep.sendKeys_aroundBody8(CommonStep.java:75)\n\tat com.infostretch.automation.step.CommonStep$AjcClosure9.run(CommonStep.java:1)\n\tat org.aspectj.runtime.reflect.JoinPointImpl.proceed(JoinPointImpl.java:149)\n\tat com.infostretch.automation.step.JavaStepReporter$MockJavaStep.doExecute(JavaStepReporter.java:89)\n\tat com.infostretch.automation.step.BaseTestStep.execute(BaseTestStep.java:96)\n\tat com.infostretch.automation.step.JavaStep.baseExecute(JavaStep.java:89)\n\tat com.infostretch.automation.step.JavaStepReporter$MockJavaStep.execute(JavaStepReporter.java:104)\n\tat com.infostretch.automation.step.JavaStepReporter.javaTestStep(JavaStepReporter.java:70)\n\tat com.infostretch.automation.step.CommonStep.sendKeys(CommonStep.java:74)\n\tat main.tc.Login_TC1.login_with_common_step(Login_TC1.java:28)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\n\tat java.lang.reflect.Method.invoke(Method.java:597)\n\tat org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)\n\tat org.testng.internal.Invoker.invokeMethod(Invoker.java:714)\n\tat org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)\n\tat org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)\n\tat org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)\n\tat org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)\n\tat org.testng.TestRunner.privateRun(TestRunner.java:767)\n\tat org.testng.TestRunner.run(TestRunner.java:617)\n\tat org.testng.SuiteRunner.runTest(SuiteRunner.java:334)\n\tat org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)\n\tat org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)\n\tat org.testng.SuiteRunner.run(SuiteRunner.java:240)\n\tat org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)\n\tat org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)\n\tat org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)\n\tat org.testng.TestNG.runSuitesLocally(TestNG.java:1149)\n\tat org.testng.TestNG.run(TestNG.java:1057)\n\tat org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)\n\tat org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)\n\tat org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)\n"
}
Мой Java код. JsonLogParser.java. Игнорируйте основную функцию. Я упростил свой код здесь.
package com.test.parser;
import java.io.FileReader;
import com.google.gson.*;
public class JsonLogParser {
String filePath = "C:\\<PATH_TO>\\sample.json";
public static void parseJSON(String filePath){
try {
// read the json file
FileReader reader = new FileReader(filePath);
JsonParser jsonParser = new JsonParser();
JsonObject jsonGObject = (JsonObject) jsonParser.parse(reader);
String result = jsonGObject.getAsJsonArray("seleniumLog").get(0).getAsJsonObject().get("result").toString();
String errorTrace;
if(result.contains("fail")){
errorTrace = jsonGObject.get("errorTrace").toString();
errorTrace.replaceAll("\n", System.getProperty("line.separator"));
String lines[] = errorTrace.split(System.getProperty("line.separator")); // did not work
// String lines[] = errorTrace.split("\n"); // did not work
// errorTrace.indexOf("\n", errorTrace.indexOf("\n") + 1); // did not work
String errorTraceCSV = lines[0]; //always returns the entire Stack Trace. I'm expecting only first line here.
System.out.println("errorTraceCSV: " + errorTraceCSV);
}
}catch (Exception e) {
System.out.println(e.toString());
}
}
}
Выше программы не могут разбить элемент errorTrace на символ новой строки. Я хочу извлечь только первую строку errorTrace из всей трассировки стека. Я попробовал почти 3-4 различных решения, предложенных на SO. Мало кто из них я упомянул выше, и никто из них не работал.
IndexOf всегда возвращает -1. Функция split получает всю трассировку стека. Таким образом, он не раскололся.
Я думаю, что я делаю какую-то тупость здесь. Любая помощь приветствуется.
С уважением, Rumit
Если вы создаете считыватель JSON, тогда новые строки должны быть неактуальны, так как ваш пример JSON может быть написан в одной строке, и он все равно будет действительным JSON. –
Я не уверен, как это важно, если мой JSON написан в одной строке. Если я открою пример JSON в веб-браузере, \ n возьмется за новый символ строки. Таким образом, функция SPLIT также должна рассматривать ее как отдельный символ и работать, как ожидалось, но это не так. Дайте мне знать, если я ничего не понял. –