Receive an AJAX HTTP POST request and process it on the backend using Java

In the process of creating a ticketing system using JavaScript/Angular for the frontend, and sending HTTP requests with AJAX. Currently, we are including parameters in the header as shown below:

  numbPass: 3
  Total Price: 39

These details belong to one order with 3 passengers. Each passenger may have a different price based on their type (regular, student, military), so dividing the total among them is not an option.

At present, these variables are received in the backend like this:

 Gson gson = new Gson();
 WalkIn walkinRequest = gson.fromJson(req.getReader(), WalkIn.class);

My goal is to send lists of passengers, which I discovered can be done like this:

var schedule = [];
    var passenger = { 
      type : 'student', 
      price' : 150,
    }
    schedule.push(passenger);

    var passenger = { 
      type : 'student', 
      'price' : 150,
    }
    schedule.push(passenger);

How can I effectively handle this data in the backend using Java (placing them into passenger objects)?

Edit: It might be a bit unclear what I'm asking. Initially, I wanted to confirm if Gson can manage processing arrays from HTTP requests. If not, then I am seeking guidance on how to address this issue. A response to this question can be found in the post below.

Answer №1

Allow me to interpret your inquiry and provide some guidance.

  1. If you are inquiring about simple deserialization, then using Gson allows you to read an array of objects in the following manner:

    WalkIn[] walkinRequests = gson.fromJson(req.getReader(), WalkIn[].class);
    
  2. If you wish to modify the structure of your WalkIn object from:

    WalkIn
        int numbPass
        int totalPrice
    

    to

    WalkIn
        PassengerWalkIn[]
        int numbPass
        int totalPrice
    
    PassengerWalkIn
        String type
        int price
    

    Gson is capable of deserializing this structure accordingly.

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

Read in a CSV document within my JavaScript application

Is there a way to import a CSV file into my program in JavaScript when I know the file path? For instance, if the path to the CSV file is C:/Users/User/example.csv, I want to be able to load it into my program like this: let MY_CSV_FILE = CSV_LOAD("C:/Use ...

I encountered an issue with Material UI tabs showing the error message: "Failed prop type: The prop `children` is not supported. Please remove it."

Recently, I started using Material UI tabs in my project for the first time. Everything seems to be working fine except for one issue that keeps showing up in the console while running the project: Failed prop type: The prop `children` is not supported. Pl ...

Combine several objects into one consolidated object

Is there a way to combine multiple Json objects into one single object? When parsing an array from AJAX, I noticed that it logs like this: 0:{id: "24", user: "Joe", pass: "pass", name: "Joe Bloggs", role: "Technical Support", ...} 1:{id: "25", user: "Jim ...

Leverage API providing HTML and JavaScript exclusively using PHP script

Seeking a way to automate the conversion process from HTML to PNG using a PHP script with a REST API. The website only provides an example using HTML and JavaScript, allowing users to upload an HTML file for conversion. My PHP script currently generates H ...

Why aren't my cookies being successfully created on the frontend of my application when utilizing express-session and Node.js?

Having trouble setting cookies while using express-session in my MERN stack project. When accessing endpoints from frontend localhost:3000 to backend localhost:8080, the cookies do not set properly. However, everything works fine when both frontend and b ...

How to send JSON data to a WebAPI endpoint using AngularJS

$scope.items = {2: true, 4: true, 5: true, 7: true, 9: true, 10: true, 11: true }; Is there a way to send the JSON data above to the WebAPI method below using angularjs's $http? [Authorize] [HttpPost] [Route("moveemployees")] public HttpResponseMess ...

Having trouble retrieving a value from a .JSON file (likely related to a path issue)

My React component is connected to an API that returns data: class Item extends Component { constructor(props) { super(props); this.state = { output: {} } } componentDidMount() { fetch('http://localhost:3005/products/157963') ...

Error: React unable to locate module './WebpackMissingModule'

Recently I started diving into React, and I'm encountering some difficulties trying to export components. Here is my current index.js file setup: import React from 'react'; import ReactDOM from 'react-dom'; import SearchBar from ...

Retrieve: Type 'string | undefined' does not match the parameter type 'RequestInfo'

When using the fetch function, I encountered an error with the "fetchUrl" argument: Error: Argument of type 'string | undefined' is not assignable to parameter of type 'RequestInfo'. This is the code snippet where the error occurred: ...

Dealing with TypeScript errors TS2082 and TS2087 when trying to assign an Away3D canvas to a variable

As a beginner with TypeScript, I am in the process of creating an Away3D scene where a canvas element is dynamically generated and needs to be appended to a container. Although the code functions correctly, I am encountering the following compilation erro ...

Utilizing Fullcalendar Qtip to display information on mouseover rather than utilizing the eventRender

I have a challenge with integrating Qtip to the eventMousever event instead of the eventRender event in fullcalendar. The main reason for this adjustment is due to the server hosting the data being located in another country, resulting in significant late ...

Attaching an Event Listener to an array

I am struggling with a homework assignment and don't understand why I am receiving an error message saying 'undefined is not an object (evaluating 'buttons[i].style')). Any help would be appreciated. I have been attempting to loop throu ...

Utilizing jQuery to apply multiple classes simultaneously?

What is the purpose of allowing multiple classes to be added? Is there any real benefit to this feature or is it just unnecessary complexity? I attempted to utilize it, but found that it serves no practical function. ...

Steps to create a thumbnail image following the insertion of an image into an input type="file" within a form, and subsequently submitting both elements on the form together

Currently, I am working on a form that enables users to upload images. Once the user submits the form, my goal is to create thumbnails for each image on the front-end and save them on the server afterwards. Due to security restrictions, changing the value ...

Merge two nested JSON arrays by overriding the values of JSON A with those of JSON B

There are two JSON arrays that need to be compared. If the "id" property in Json A matches the "id" property in Json B, then override the values of the properties in Json A with the values of the properties in Json B. Here is the JSON A Array: { "com ...

Using Python on a webpage to establish a connection between a smartphone and a computer

Although the title may be misleading, I have a query regarding the feasibility of having a Python script embedded on my website to determine if my Android phone is linked to the computer from which I am accessing the page. I am unsure if this can be achi ...

Comparing prevProps and this.props in React Native Redux: What is the most effective method?

Does anyone know how to efficiently handle triggering a function in my React Native app only when a specific prop has changed? This is the current implementation I have: componentDidUpdate(prevProps) { if (prevProps.a !== this.props.a) { <trigger ...

Utilizing jQuery Autocomplete to access JSON data via an API

My understanding of jQuery autocomplete is a bit limited, so I'm hoping for some guidance on how to achieve my task. I currently have the following URL: http://localhost/contactApi.do?mobile=614321 This URL allows for inputting either a complete or ...

Uncover the issue with the examination: solving the enigma of the ancient wizards' sect

I am attempting to crack this enigma in Java, revolving around an elderly man sustained by his cult members who share their life force with him. The code provided must adhere to the specified rules, but there seems to be an error during testing. public cla ...

Unleashing the potential of extracting the value of a subsequent iteration while within the

Currently, I am facing a dilemma as I am unable to comprehend the logic required to design this algorithm. The problem at hand involves a sequence of images with arrows placed alternatively between each image. The structure appears as follows: Image -> ...