Please ask Java to receive a JSON parameter for converting a JSON array into a Java array

Essentially, my goal is to pass a Java String array to a JavaScript array, then pass this array via JSON to a JSP page, where I can parse it as a Java array.

I attempted the following:

JSONArray arr = new JSONArray();
JSONObject tmp;

    for(int i = 0; i < invoiceid.length; i++) {
         tmp = new JSONObject();
         tmp.put("invoiceid", invoiceid[i]);
         arr.add(tmp);
    }

Next, here is the JavaScript code on the same page:

var invoiceid = JSON.stringify(<%=arr%>);`
$.ajax({
                     type: 'GET',
                     url: 'crudsettlement.jsp',
                     data: {
                         Winvoiceid: invoiceid
                     },
                     async: false,
                     dataType: 'json',
                     success: function(json) {
                         $("#msg").val(json.msg);
                     }
                 });

In the page crudsettlement.jsp, I attempted the following:

JSONObject jObj = new JSONObject(request.getParameter("mydata"));

However, I encountered the error: "incompatible types: String cannot be converted to Map."

Do you have any ideas on how to convert the JSON array to a Java array? I am using json-simple.

Answer №1

Not very familiar with JSON, but here is a basic approach:

JSONArray arr = new JSONArray(request.getParameter("mydata"));
List<String> jsonList = new ArrayList<String>();
for (int i = 0; i < arr.length(); i++) {
    jsonList.add(arr.getJSONObject(i).getString("invoice"));
}
String[] invoices = jsonList.toArray(new String[0]);

Update, I tested the following and it appears to be functional:

String json = " [{\"invoiceid\":\"0147708\"}]";

JSONArray array = (JSONArray) new JSONParser().parse(json);

List<String> jsonList = new ArrayList<String>();
for (int i = 0; i < array.size(); i++) {
    jsonList.add(((JSONObject) array.get(i)).toString());
}
String[] invoices = jsonList.toArray(new String[0]);

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

Problems arise with identification of asynchronous functions

My async functions have been used successfully in various projects, but when incorporating them into a new project, they suddenly stopped working. One of the functions causing trouble is: const ddbGet = async (params) => { try { const data ...

"Is there a way to transmit a JSON with just one word (without a key) to springMVC

I am facing a challenge with my API for the front end. Currently, I am using Postman to send a single number (8). I am looking to implement a similar process in Postman @RequestMapping(value="/query",method=RequestMethod.POST) @ResponseBody public String ...

Executing a function within a VueJs 2 component immediately after it has finished loading

How can I retrieve data after a component has finished loading? When I initialize my Vue instance and load the component, the template loads correctly but the functions in the mounted lifecycle hook are not executed, causing the stats object to remain empt ...

Issue encountered: The function car.reviews.find() is not recognized

Encountering an issue with the find() method in my MERN stack application. I am looking to implement a reviews route where users can add comments about cars within the app. In the frontend, fields and buttons have been added; meanwhile, a post request has ...

"Creating dynamic web apps with the powerful duo of Meteor and Zurb

Just starting out with programming and currently working on a new web application using Meteor and AngularJS. I would like to incorporate the elements/css from 'Zurb Foundation For Apps' into my project... I am familiar with including Bootstrap ...

Exploring innovative CSS/Javascript techniques for creating intricate drawings

When using browsers other than Internet Explorer, the <canvas> element allows for advanced drawing. However, in IE, drawing with <div> elements can be slow for anything more than basic tasks. Is there a way to do basic drawing in IE 5+ using o ...

Starting a tab just once

I have successfully created 4 static HTML pages that include: Home About Services Contact Each page contains a link that leads to another static page named myVideo.html, which plays a video about me in a new tab. The link is available on every page so ...

Mastering Yii2: Implementing Javascript Functions such as onchange() in a View

One of the elements in my project is a checkbox: <div class="checkbox"> <label> <?= Html::checkbox('chocolate', false) ?> Chocolate </label> </div> In addition to that, I also have a span ta ...

Gather Different Data Fields and Combine them into a Fresh Object from MongoDB

I have a simple question regarding my MongoDB structure that I hope can be answered easily. My structure looks like this: { ... a: [array elements], b: [array elements], c: [array elements], ... } Currently, I am using Mongoose and making 3 d ...

Tips for incorporating error messages based on specific errors in HTML

In the current setup, a common error message is displayed for all errors. However, I want to customize the error messages based on the specific type of error. For example, if the password is invalid, it should display "invalid password", and for an invalid ...

java code for clicking all buttons with identical class

I have been attempting to select and click all buttons that share the same class. For instance: I am trying to select and click all buttons across the page with a specific class. I'm unsure if this is possible with the emulator or if there is a way to ...

Incorporate query strings into every hyperlink within the application

Let me paint you a picture... I've got this lovely Next.js app that's been around for a while, filled with lines of code we've poured our hearts into. Recently, we decided to spice things up by running some ads and now we are itching to see ...

I possess an item that I must display its title as a <choice> in a <menu> while returning a different variable

I am working with an object: company: { name: 'Google', id: '123asd890jio345mcn', } My goal is to display the company name as an option in a material-ui selector (Autocomplete with TextField rendering). However, when a user selects ...

What are the steps to incorporate ThreeJS' FontLoader in a Vue project?

I am encountering an issue while attempting to generate text in three.js using a font loader. Despite my efforts, I am facing difficulties in loading the font file. What could be causing this problem? const loader = new FontLoader(); loader.load( ' ...

Updating the text of an element will occur only when the specified condition has been met

I am trying to dynamically change the text within the <span data-testid="recapItemPrice">ZADARMO</span> element from 'ZADARMO' to 'DOHODOU' only when the text inside the parent element 'INDIVIDUÁLNA CENA PREP ...

Changing individual JPanels within a JFrame

I have a main window with two distinct panel components. The first panel consists of various clickable buttons, while the second panel contains input text fields. I have attached mouse listeners to the buttons through the main window and now I want to up ...

Sending data from PHP to JavaScript using JSON encoding through POST requests

I am dealing with a multi-dimensional array that needs to be passed to a PHP script using JavaScript to parse JSON data and display it on Google Maps. I am experimenting with using forms to achieve this: <?php $jsontest = array( 0 => array( ...

Having trouble reaching an injected dependency beyond the controller method

Can an injected dependency on a controller be accessed outside of it? function clientCreateController(ClientsService, retrieveAddress) { var vm = this; vm.searchCep = searchCep; } function searchCep(cep) { retrieveAddress.find(cep) .success ...

Troubleshooting ASP.NET MVC3: The mystery behind why my custom validation attributes always seem to fail

After completing several tutorials, I have successfully implemented my models from a library file (dll). Everything seems to be functioning correctly except for one issue. Here is my model: public class RoomBookingInsert { public Int32 CostCentreNo ...

How do I handle the error "Uncaught TypeError: Cannot read property 'func' of undefined in React JS

Hey there, I've encountered an issue while setting up a date picker on my project. I tried using these resources: https://github.com/Eonasdan/bootstrap-datetimepicker Would appreciate any help! https://codesandbox.io/s/18941xp52l render() { ...