3

I'm trying to find the easiest way to parse simple json to java Object for use json data in autotest (TestNG), but I don't understand another examples with various libraries.

I have this code:

@Test(dataProvider = "SearchData") 
public void searchCatTest(String searchRequest, int expectedVal) {
    CatScreen.search(searchrequest);
    int actualVal = CatScreen.getSearchResultsNumber();
    Assert.assertEquals(actualVal, expectedVal);
}

And I have this json:

{   "dataSet": [
    {
      "searchRequest": "*]",
      "expectedVal": 0
    },
    {
      "searchRequest": "Tom",
      "expectedVal": 1
    },
    {
      "searchRequest": "1234",
      "expectedVal": 0
    }   ] }

How can I linked them?

djangofan
  • 28,471
  • 61
  • 196
  • 289
Dmitrij
  • 51
  • 1
  • 6
  • I think the question is to broad and an answer would be opinionated. Here is a good answer how to parse JSON: https://stackoverflow.com/questions/2591098/how-to-parse-json-in-java – brass monkey Jul 19 '18 at 09:59

2 Answers2

2
@DataProvider(name = "json-data")
public static Object[][] getJSON(ITestContext context) throws FileNotFoundException {
    String filename = <get name from context>
    JsonArray array = new JsonParser().parse(new FileReader(filename))
       .getAsJsonArray();
    Gson gson = new Gson();
    List < Map > list = gson.fromJson(array, List.class);
    Object[][] objects = list.stream()
        .map(testData - >
            testData.values().stream().map(obj - > 
              doubletoint(obj)).toArray()).toArray(Object[][]::new);
    return objects;
}

TestNG will create a new thread per row of data.

djangofan
  • 28,471
  • 61
  • 196
  • 289
Dmitrij
  • 51
  • 1
  • 6
0

You can use the following library to parse the json code to java :

        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>

You can refer the this link for how to parse the json code.

Suraj Jogdand
  • 308
  • 2
  • 17
  • Thanks, but this info is more than available in google. I search a simple and fast template for this actions: parse json array to java Object[][] – Dmitrij Jul 19 '18 at 07:58