java - 无法从JSON在换行符上拆分字符串

时间:2014-06-30 05:17:01

标签: java regex json string split

我正在编写一个简单的java程序来读取JSON文件并从中提取某些信息。但是,String的split函数不会在new line OR \n字符上拆分字符串。

以下是我的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的第一行。我在SO上尝试了近3-4种不同的解决方案。我上面提到的很少,但没有一个能奏效。

indexOf始终返回-1。 split函数获取整个堆栈跟踪。所以,它根本不会分裂。

我想我在这里做了一些愚蠢的事。任何帮助表示赞赏。

此致 Rumit

1 个答案:

答案 0 :(得分:0)

尝试使用

进行拆分
split("[\\r\\n]+")

而不是两行

errorTrace.replaceAll("\n", System.getProperty("line.separator"));
String lines[] = errorTrace.split(System.getProperty("line.separator")); // did not work

使用此

String lines[] = errorTrace.split("[\\r\\n]+");

它应该有希望。

相关问题