Pristin
Pristin

Reputation: 185

How to retrieve data from data table dynamically?

I have a datatable like so:

|quotes|
|quote_a|
|quote_b|
|quote_c|

I want to retreive all these quotes from data table and pass them in a json request body. Now I know how to do grab each individual item via data.get(0), data.get(1) and data.get(2) but this isn't really dynamic.

i want to use a dynamic way of retrieving all quotes from the data table, placing them in an away with a comma separate and place all of that in the body.

How can I change the below to achevice this?

@When("^get quote)
    public void getQuotes(DataTable dataTable)
        throws Throwable
{

        List<List<String>> data = dataTable.raw();
        List<String> quotesList = new ArrayList<>();
        for (String quotesStr : data) {
            quotesList.add(quotesStr);
        }

        requestSpecificationFacade.body("{\n" +
           " \"quoteId\": " + data.get(0) + ", " + data.get(1) + ", " + data.get(2) +  "\n" +
                                            "}");


        }

Upvotes: 0

Views: 225

Answers (1)

Nesku
Nesku

Reputation: 501

If I understand correctly you have a list of string and want to transform it to a single string separated by comma (and space) dynamically.

You can do this using Java 8 with String.join :

String output = String.join(", ", data);
requestSpecificationFacade.body("{\n" +
                   " \"quoteId\": " + output +  "\n" +
                                                    "}");

Or using Java 7 with a StringBuilder :

StringBuilder outputBuilder = new StringBuilder();
for (String quote : data) {
    outputBuilder.append(quote);
    outputBuilder.append(", ");
}
String output = outputBuilder.toString();

// Remove last comma
output = output.substring(0, output.length() - ", ".length());

requestSpecificationFacade.body("{\n" +
           " \"quoteId\": " + output +  "\n" +
                                            "}");

In both case output will return quote_a, quote_b, quote_c.

Upvotes: 1

Related Questions