Skip to content
Advertisement

casting of js.executeAsyncScript output to Map

I want to cast the output of below script into Map<string,string> but it is showing “java.lang.String cannot be cast to java.util.Map“error. How can we cast that in map??

final JavascriptExecutor js = (JavascriptExecutor) driver;
            Map<String,String> str = new HashMap<>();
            str = (Map<String, String>) js.executeAsyncScript("var myHeaders = new Headers();n" +
                    "myHeaders.append('client-id', 'LPDP');n" 
                    "let inputEntities = new Map();n" +
                    "inputEntities.set("Commons$customerId", "\"A2ZLDCQRXMMNLG\"")n" +
                    "inputEntities.set("Commons$marketPlaceId", "\"A2XZLSVIQ0F4JT\" +
                    "let entitiesToBeResolved = ["Rewards$APPA$GetAllPromotions$applicablePromotionDetailList"]n" +
                    "n" +
                    "const executeInput = {n" +
                    ""inputEntities": Object.fromEntries(inputEntities),n" +
                    ""entitiesToBeResolved": entitiesToBeResolved,n" +
                    "};n" +
                    "var obj n" +
                    "n" +
                    "fetch("url", {n" +
                    "  method: 'POST',n" +
                    "  headers: myHeaders,n" +
                    "  body: JSON.stringify(executeInput),n" +
                    "})n" +
                    "  .then(response => response.text())n" +
                    "  .then(arguments[0])n" +
                    "    .then(result => obj = result);n" +
                    "n" +
                    "  return obj;");

Advertisement

Answer

I assume your response is in Json format. You can use Gson to convert the String to Map.

import com.google.gson.Gson;

Map<String, String> str = new HashMap<String, String>();
String response = js.executeAsyncScript("....");
str = new Gson().fromJson(response, HashMap.class);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement