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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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[][]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.