Tips for properly formatting a Map<Entity,integer> within a json payload

I'm currently working on sending an entity named "order" from a client to the Rest/Api Spring Boot Back-End. Within my OrderEntity, there is a Map containing the products of that order.

We are using Postman software to create a correct JSON string that we want to include in the body of a POST request.

@ElementCollection
@CollectionTable(name = "product.order", joinColumns = @JoinColumn(name = "order.id"))
@MapKeyJoinColumn(name = "product.id")
@Column(name = "quantity")
//@JsonSerialize(keyUsing = ProdottoMapSerializer.class)
@JsonDeserialize(keyUsing = ProdottoMapDeserializer.class)

OrderEntity

public OrderEntity(Map<ProductEntity, Integer> product, ClientEntity cliente,Integer id, String data, Float totale, String fattura) {
        this.product = product;
        this.client = client;
        this.id = id;
        this.data = data;
        this.total = total;
        this.invoice = invoice;
    }
@ManyToOne
private ClientEntity client;

ProductEntity

public ProductEntity(Integer id, String name, String description, String category, Float price, String photo,
            Integer stockQuantity, Integer fastShipping) {
        this.id = id;
        this.name = name;
        this.description = description;
        this.category = category;
        this.price = price;
        this.photo = photo;
        this.stockQuantity = stockQuantity;
        this.fastShipping = fastShipping;
    }

When making a POST request with JSON, the body should be formatted like this:

{
    "id": 10,
    "date": "2019-07-11 00:00:00",
    "total": null,
    "invoice": null,
    "product": {
        "ProductEntity{id=4, name='oneplus 6t', description='smartphone', category='electronics', price=500.0, photo='', stockQuantity=4, fastShipping=0}": 2
    },
    "client": {
        "id": 3
    }
}

The "product" field is causing an error due to incorrect formatting. This is the specific problem:

"status": 400,
"error": "Bad Request",
"message": "JSON parse error: For input string: \"ProductEntity{id=4, name='oneplus 6t', description='smartphone', category='electronics', price=500.0, photo='', stockQuantity=4, fastShipping=0}\"; nested exception is com.fasterxml.jackson.databind.JsonMappingException

Below is the post request being made:

 @PostMapping("/postorder") //PROVA aggiunge un ordine 
 public ResponseEntity<?> postOrder(@RequestBody OrderEntity order){

     orderRepository.save(order);

     return new ResponseEntity<>(Collections.singletonMap("id", order.getId()),HttpStatus.CREATED)

Answer №1

It seems like you forgot to include a : in the ProductEntity, causing it not to be parsed correctly during mapping. Give it a try and see if this resolves the issue. I haven't tested it myself so let me know how it goes.

{
    "id": 10,
    "data": "2019-07-11 00:00:00",
    "totale": null,
    "fattura": null,
    "product": {
        "ProductEntity: {id=4, nome='oneplus 6t', descrizione='smartphone', categoria='elettronica', prezzo=500.0, foto='', quantitaMagazzino=4, spedizione_veloce=0}": 2
    },
    "cliente": {
        "id": 3
    }
}

Answer №2

Ensure that your ProductEntity has the @JsonDeserialize annotation and try using this specific JSON structure to check if it resolves the issue

  {
    "id": 10,
    "data": "2019-07-11 00:00:00",
    "totale": null,
    "fattura": null,
    "product": {
        "{id=4, nome='oneplus 6t', descrizione='smartphone', categoria='elettronica', prezzo=500.0, foto='', quantitaMagazzino=4, spedizione_veloce=0}": 2
     },
     "cliente": {
         "id": 3
     }
 }

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 Laravel 5.3 and Vue.js for Dynamic AJAX Calls Based on Select Box Selections

I am looking to display a newly added record in a select box once it has been inserted into the table. Below is my Laravel HTML code: <div class="form gorup"> <select class="form-control" > <option @click="called" ...

How can we generate three planes in geometric space that are perpendicular to the x, y, and z

I have been tasked with creating three plane geometries in a scene, one perpendicular to the x-axis, one perpendicular to the y-axis, and one perpendicular to the z-axis. The desired result should somewhat resemble this image: https://i.sstatic.net/L1K6G.p ...

Verify the presence of a specific value within an array of objects in JavaScript that was retrieved from an AJAX response, and then

I am encountering an issue with the code below where I am unable to filter entry.AllLinks. The code snippet is shown here: $.ajax({ url: url, type: "get", headers: {"Accept": "application/json;odata=verbose"}, success: function (data) { ...

The destruction of scope is not activated

Check out my issue in action with this plunkr demo. The problem I'm encountering is quite straightforward: manually calling $destroy or removing the element does not trigger the $destroy event. function link(scope, element, attrs) { // Manually ca ...

Exploring ways to compare and update values in an array of objects using JavaScript

I have a situation where I need to compare the names and values of two arrays filled with objects. const array1 = [ { name: 'Sarah', value: null }, { name: 'Michael', value: null } ] const array2 = [ { na ...

Rails 7 is missing the Toast element from Bootstrap 5

Having some trouble with implementing Bootstrap 5 Toast in Rails 7 for flash messages. Here is the code I am currently using: # application.html.erb <head> ... <%= javascript_importmap_tags %> <script> const toastElList = document.que ...

Incorporating a dynamic URL within a script tag with AngularJs

I am currently integrating a payment gateway into my Single Page Application (SPA) using AngularJS. The issue I'm facing is that the payment gateway requires me to include a script with a specific ID for the payment process to work correctly. This i ...

Hybrid component that combines static and dynamic elements in Gatsby

The inconsistency in behavior between the site generated by gatsby develop and gatsby build is causing an issue where the site works during development but not when it's in production. An overview of my website: My website is a simple blog-like plat ...

Ensuring parameter validity at compile time when passing arguments to a function in Kotlin for Android development

Currently, I am utilizing a JSON file as an input for a class and using gson to parse the values through respective data classes. I am interested in invoking a function that requires a String value as an argument. The permissible string value is determin ...

Creating a cascading layout with React Material-UI GridList

Can the React Material-UI library's GridList component be used in a layout similar to Pinterest's cascading style? I have utilized Material-UI Card components as children for the GridList: const cards = props.items.map((item) => <Card ...

Tips for accessing data from a database with ajax/json in the jQuery Week Calendar

My current project involves adapting a jQuery calendar module to work with PHP and MySQL. The issue I'm facing is that the code loads events in a specific format: return { events : [ { "id":1, "start": new Date(ye ...

utilize dynamic variables in post-css with javascript

Question: Is it possible to dynamically set or change variables from JavaScript in post-css? I have a react component with CSS3 animations, and I want to set dynamic delays for each animation individually within each component. I've found a similar s ...

Having trouble accessing the hyperlink with the click of a button

Currently, I am working on writing Selenium code that will allow me to click on "Edit" for a specific group from a list of group names. I have successfully located the Edit link using the Xpath, which appears to be correct when verified with an Xpath check ...

Is there a way to divide a single array into two separate arrays based on a specific element?

My goal is to create an interactive graph using plotly.js. I have an array named data that contains all the information needed for the graph. However, I want users to be able to select specific elements to display on the graph. To achieve this functionalit ...

Retrieving information from the API to populate a child component in Next.js

I have been developing a header component and here's the code snippet: import style from '../../styles/header.css'; import '../../styles/globals.css'; export default function Header({data}){ const [showMe, setShowMe] = useStat ...

Creating a Hidden Button on Your PWA: A Step-by-Step Guide

After creating a React app with Create React App, I decided to use the default PWA configuration. However, I am facing some confusion regarding how to hide the "Add to Home Screen" button. Can anyone provide some guidance on this issue? Thank you. https: ...

Tips for implementing multiple middlewares in Next.js using the middleware.ts script

In the development of my Next.js project, I am exploring the implementation of multiple middleware without depending on external packages. Although I have seen examples of using a single middleware in Next.js with the next-connect package, I aim to achieve ...

Is it really necessary to still think poorly of JavaScript in 2011?

Here's an intriguing question for you. I've tested out a variety of popular websites, including Facebook, and I've noticed that many features still work perfectly fine even when JavaScript is disabled. People always used to say that JavaScr ...

Understanding how to handle errors in Javascript using promises and try/catch statements

Seeking assistance because I'm having trouble grasping a concept... Here's the code snippet: // AuthService.js login(user) { return Api.post('/login', user); }, // store/user.js async login(context, user) { try { let ...

What is the best way to transfer attribute values from multiple elements and paste them each into a separate element?

I have multiple elements with the tag <a class="banner2">. Each of these elements has a different URL for the background image and href value. <a href="#" target="_blank" class="banner2" style="background-image:url('<?php echo get_templat ...