简体   繁体   English

将JSON数据读入Java对象

[英]Reading json data into java objects

I am reading data from Excel using java into a json array like this: 我正在使用Java从Excel读取数据到json数组中,如下所示:

 FileInputStream inp = new FileInputStream("C://temp/testdata.xls");
            HSSFWorkbook workbook = new HSSFWorkbook(inp);

            // Get the first Sheet.
            Sheet sheet = workbook.getSheetAt(0);

            //Start constructing JSON.
            JSONObject json = new JSONObject();

            // Iterate through the rows.
            JSONArray rows = new JSONArray();

            for ( Iterator<Row> rowsIT = sheet.rowIterator(); rowsIT.hasNext(); )
            {
                Row row = rowsIT.next();
                JSONObject jRow = new JSONObject();

                // Iterate through the cells.
                JSONArray cells = new JSONArray();
                for ( Iterator<Cell> cellsIT = row.cellIterator(); cellsIT.hasNext(); )
                {
                    Cell cell = cellsIT.next();
                    cells.put( cell.getStringCellValue() );
                }
                jRow.put( "cell", cells );
                rows.put( jRow );
            }

            // Create the JSON.
            json.put("rows", rows);

            myvalue = json.toString();
            System.out.println(myvalue);

My excel file looks like this: 我的Excel文件如下所示:

TestCase    SearchString    PageTitle
TC1.01          Ferrari         Ferrari - Google Searching
TC1.02          Toyota          Toyota - Google Searching
TC1.03          Mazda           Google
TC1.04          Volvo           Google

First row is my column names. 第一行是我的列名。

When I print my values out I get this: 当我打印出值时,我得到了:

{"rows":[{"cell":["TestCase","SearchString","PageTitle"]},{"cell":["TC1.01","Ferrari","Ferrari - Google Searching"]},{"cell":["TC1.02","Toyota","Toyota - Google Searching"]},{"cell":["TC1.03","Mazda","Google"]},{"cell":["TC1.04","Volvo","Google"]}]}

How do I map the column names with the data in java? 如何将列名称与Java中的数据映射? For example: How can I map the SearchString column with Ferarri? 例如:如何将SearchString列与Ferarri映射? (and so on) (等等)

Would appreciate any help :-) 将不胜感激:-)

I don't think you can do so directly with normal JSON library. 我认为您不能直接使用普通的JSON库执行此操作。

Try to handle the "header" line separately when you are reading from the Excel and constructing the JSON. 从Excel读取并构造JSON时,请尝试分别处理“标题”行。 You should try to produce a JSON looks like this: 您应该尝试生成如下所示的JSON:

{"rows":[
    {
        "TestCase"      : "TC1.01",
        "SearchString"  : "Ferrari",
        "PageTitle"     : "Ferrari - Google Searching"]
    },
    {
        "TestCase"      : "TC1.02",
        "SearchString"  : "Toyota",
        "PageTitle"     : "Toyota - Google Searching"]
    },
    {
        "TestCase"      : "TC1.03",
        "SearchString"  : "Mazda",
        "PageTitle"     : "Google"]
    },
    {
        "TestCase"      : "TC1.04",
        "SearchString"  : "Volvo",
        "PageTitle"     : "Google"]
    }
    ]
}

(every data row become a map and having key as the column name) (每个数据行都变成一个映射,并以键作为列名)

Then mapping this to a POJO should be trivial with any of the JSON libs. 然后,使用任何JSON库将其映射到POJO都是不重要的。

Thanks for all your replies. 感谢您的回复。

I ended up doing something like this which works for me. 我最终做了这样对我有用的事情。

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import java.io.FileInputStream;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Excel_Example {

   @Before
   public void setup(){         
       System.setProperty("webdriver.chrome.driver", "C://temp/chromedriver/chromedriver.exe");
   }

    @Test
    public void test() throws JSONException {

        try {
         // Open the Excel file
            FileInputStream fis = new FileInputStream("C://temp/testdata.xls");
            // Access the required test data sheet
            HSSFWorkbook wb = new HSSFWorkbook(fis);
            HSSFSheet sheet = wb.getSheet("testdata");
            // Loop through all rows in the sheet
            // Start at row 1 as row 0 is our header row
            for(int count = 1;count<=sheet.getLastRowNum();count++){
                HSSFRow row = sheet.getRow(count);
                System.out.println("Running test case " + row.getCell(0).toString());

                //Start constructing JSON.
                JSONObject json = new JSONObject();
                json.put("SearchString", row.getCell(1).toString());
                json.put("PageTitle", row.getCell(2).toString());                  

                // Run the test for the current test data row
                runTest(json.getString("SearchString").toString(),json.getString("PageTitle").toString());

            }
            fis.close();
        } catch (IOException e) {
            System.out.println("Test data file not found");
        }                                     

} }

    public static void runTest(String strSearchString, String strPageTitle) {

        // Start a browser driver and navigate to Google
        WebDriver driver = new ChromeDriver();
        driver.get("http://www.google.com");

        // Enter the search string and send it
        WebElement element = driver.findElement(By.name("q"));
        element.sendKeys(strSearchString);
        element.submit();

        // Check the title of the page
        if (driver.getTitle().equals(strPageTitle)) {
            System.out.println("Page title is " + strPageTitle + ", as expected");
        } else {
            System.out.println("Expected page title was " + strPageTitle + ", but was " + driver.getTitle() + " instead");
        }

        //Close the browser
        driver.quit();
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM