Convert js.executeAsyncScript result into a Map with key-value pairs of strings

Trying to convert the output of the script below into a Map<string,string>, but encountering an error that says "java.lang.String cannot be cast to java.util.Map". How can I successfully cast it as a 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;");

Answer №1

Assuming the data you are working with is structured in JSON format, you have the option to utilize the Gson library to easily convert the data from a String to a Map.

import com.google.gson.Gson;

Map<String, String> dataMap = new HashMap<String, String>();
String responseData = js.executeAsyncScript("....");
dataMap = new Gson().fromJson(responseData, HashMap.class);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Selenium in Python to engage with pop-up windows

Currently, I am working on a project that involves using the Selenium module in Python to extract data from one website, save it as a text list, and then navigate to another site to submit this text list. The script is divided into two parts: 1. Getting me ...

Using a Bearer Token for a Retrofit Request

I am currently attempting to execute a post request with a Bearer token included. When I make the call using Postman, it is successful. This is my interface: public interface UserClient { // @FormUrlEncoded // @Headers({ "Content-Type: ap ...

Selenium is having difficulty identifying elements on the HTML page

Currently, I am working on developing a small Java application that can log in to my university's portal. In order to achieve this functionality, I utilized Selenium, as shown in the code snippet below: //import statements public class Portal{ ...

Is there a way to ensure that an external file function completes before proceeding with the main code execution?

In my project, I have two key JavaScript files: main.js and load.js. Within load.js, there are two essential functions - getData, which makes an AJAX post call, and constHTML, which appends data based on the JSON array returned from the AJAX call. This app ...

Exploring the possibilities of node-webkit: node-odbc encounters a setback

Currently, I'm in the process of developing a desktop application utilizing node-webkit. The main functionality of the app involves querying an Oracle database. To establish the connection with the database, I have integrated node-odbc. To ensure tha ...

Generate HTML tags dynamically within a JSON document using PHP

Is there a way to incorporate HTML markups (generated dynamically by a CMS) into a JSON file? I am aware that in the html string, one must escape double quotes by adding "" as shown below. { "title": "Title", "da ...

Tips for locating the highest value within an array, encompassing numerical values

I am looking for a way to identify the maximum negative value in an array of length 5, regardless of whether the integers in the array are positive or negative. I understand this should be straightforward, but any guidance you can offer would be greatly ...

Troubleshooting Spring JMS MappingJackson2MessageConverter: Dealing with error handling limitations

In my implementation using Spring JMS, I have configured the MappingJackson2MessageConverter to facilitate message exchange between different components. The main issue I am facing is that when the MappingJackson2MessageConverter encounters an internal de ...

What is the formula for determining the size of an image using JavaScript, jQuery, or Java?

I'm looking to determine the dimensions of an image. I have both the image src and base64 data available. My goal is to display the current size of the image. I am working with Java and JavaScript. Is there a way for me to calculate the image size usi ...

The evaluate function is not functioning as expected

Code: console.log(propertyName); console.log(eval(this.state.propertyName)) console.log(this.state.DriverFirstName); Output: DriverFirstName undefined fsdfds I am attempting to access a variable defined by a string value (propertyNa ...

How to troubleshoot incorrect div width detection by jQuery in Bootstrap

My asp.net mvc4 project utilizes bootstrap for markup and jquery for client side functionality. <div class="row"> <div class="col-md-4 container" id="cont"> <div class="row overlay_container" id="overlayCont"> <div class=" ...

What is the best way to retrieve a single value from an SQLite database in an Android

I'm having trouble running this code: AppsDbHelper dbHelper = new AppsDbHelper(mContext); SQLiteDatabase database = dbHelper.getReadableDatabase(); String query = "select launch from apps where name=com.google.android.apps.ma ...

Update the style class of an <img> element using AJAX

My success with AJAX enables PHP execution upon image click. However, I seek a real-time visual representation without page reload. Thus, I aim to alter <img> tag classes on click. Presently, my image tag resembles something like <img title="< ...

jQuery Each Loop failing to retrieve data during iteration

Encountered a peculiar issue while working with an each loop. The situation may seem a bit tangled but I'm constrained to manipulating the code with jQuery due to it being part of a larger framework that can't be modified. As a way to simplify t ...

Troubleshooting problem with Ajax responseText

Can an ajax responseText be received without replacing the existing content? For instance: <div id="content"> <p>Original content</p> </div> Typically, after running an ajax request with a responseText that targets id="conten ...

use ajax to dynamically append a dropdown menu

Currently working on creating a form that includes a dropdown menu populated with elements from a database. The challenge I'm facing is ensuring that once an element is selected from the dropdown, another one appears dynamically. My goal is to use AJA ...

Do not use npm to install underscore libraries

How can I resolve the error I encountered while attempting to install packages using npm? Here is my packages file: "dependencies": { "express": "~3.3.6", "socket.io": "0.9.16", "jade": "~0.35.0", "less-middleware": "~0.1.12", "redis ...

Having trouble pinpointing the elusive element in Selenium?

<div style="overflow:hidden;height:20px;" valign="middle"> <div id="IconImg_iconMenu_icon__dhtmlLib_274" class="imo" style="width:16px;height:16px;background- image:url('images/main/galleries/icon16x16gallery1b.png');background- positi ...

What is causing the PUT request to not go through when using POSTMAN?

As I navigate through the paths of my application, I encountered an issue with PUT requests that were not being fully processed by POSTMAN. Below is the configuration of my ExpressJS server: const express = require('express'); const morgan = re ...

A directive containing a template

I'm facing a unique challenge where I have to nest a template inside another template within my directive. The issue arises because AngularJS doesn't recognize ng-repeat code inside attributes. In an ideal scenario, here is how I envision my cod ...