From TypeScript Map to Java Map: A Comparison of Map Types

I need to make a call to a Java API from my Angular 2 application. I have utilized a TypeScript Map to send the request in the Java app.
The RestEndpoint in Java looks like this:

@PostMapping(value = Constants.PATH_BASE + "/sync/list")
public ResponseEntity<?> configureQueueList(@RequestBody Map<String,Integer> map){
   //code here 
    }

However, I encountered an error when attempting to use the TypeScript map:

JSON parse error: Can not deserialize instance of java.util.LinkedHashMap out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.LinkedHashMap out of START_ARRAY token\n at [Source: java.io.PushbackInputStream@f6b068c; line: 1, column: 1]

When using Postman, I found that the following raw body works:

{
 "key1":"value1",
 "key2":"value2",
 .....
 .....
}

Edit 2: Type Script Endpoint

postMap(value:Map<string,number>){
    let headers = new Headers({ 'Content-Type': 'application/json' });

            let options = new RequestOptions({ headers: headers });
            return this.http.post(this.url, value, options)
            .map(success => success.status)
                .catch(this.handleError);
}

Answer №1

Kindly ensure that your request body begins with the { tag instead of [. In Postman, wrap your request with { }; an error message indicates:

[JSON parse error: Can not deserialize instance of java.util.LinkedHashMap out of START_ARRAY token;...

...Source: java.io.PushbackInputStream@f6b068c; line: 1, column: 1]

This suggests your request is wrapped in [ ] tags

UPDATE (responding to your initial comment): Translate your Map into an Object. One way to do this is using the following function:

function mapToObj(strMap) {
        let obj = Object.create(null);
        for (let [k,v] of strMap) {
            obj[k] = v; //take note! Key must be a string!
        }
        return obj;
    }

Subsequently, input the transformed result into the http.post line

UPDATE 2 The previous solution caters to es6 usage; for es5, consider employing a dictionary like so:

let map:{ [name: string]: number }={};
map["key1"]=value1;
map["key2"]=value2;

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

The error message "Type 'string[]' does not match type 'string' in NestJS" indicates a type mismatch between a string array and a single

I am attempting to download a file by utilizing an external API in NestJS. Here is the snippet of code from my service: import { Injectable } from '@nestjs/common'; import * as fs from "fs"; import * as axios from "axios"; @Injectable() export cl ...

I'm experiencing an issue with redirect in Nextjs that's causing an error message to appear. The error reads: "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

I'm currently diving into the world of NextJS and working on creating a simple recipe application. Utilizing the new App Router has been smooth sailing for the most part, except for one hiccup with the login function. After successfully logging in (us ...

In Firebase, the async function completes the promise even as the function body is still executing

I'm currently facing an issue with an async function I've written. It takes an array of custom objects as an argument, loops through each object, retrieves data from Firestore, converts it into another custom object, and adds it to an array. The ...

How to stop a component template in Angular from displaying both conditional statements simultaneously?

I want to prevent my component template from briefly displaying both conditional statements when the condition changes after the component has been initialized. My application receives a token, and depending on its validity, it shows the appropriate conte ...

Encountering a bug in Angular 11 while fetching data from the backend to display on the screen - facing an issue with trying to access property 'values' of an undefined variable

I am currently working on retrieving data from the backend/api and attempting to display it using *ngFor. However, I am encountering the following errors: Cannot read property 'values' of undefined Below are the components, service codes, and ...

Can modifications be made to a page's source content variable using Ajax?

Can modifications be made to the source content of a page through Ajax loaded by a jsp include in the main jsp? If not, is it possible to refresh only that portion of the page (the jsp that loads some of the content) and have a portion of the content in t ...

Determine the accurate data type while iterating through a for loop

I am facing an issue where I have around 40 unique actions defined, all with the same parameters except for each being provided with a different schema which is causing the problem type ActionName = 'replaceText' | 'replaceImage'; type ...

Troubleshooting problem related to handling several Volley requests simultaneously

There seems to be an issue with my Volley request in response to user input - I have to press the button twice instead of just once to receive the desired response. Even after trying to use the wait() function, the problem persists and my application beco ...

In Typescript, it is not permitted to assign a variable as a value within a styled array

Encountering a peculiar issue with TypeScript, Emotion.css, and React. The following code functions without any issues: import styled from '@emotion/styled-base'; const Layout = styled('div')([ { height: 48, color: ...

How to locate a webpage's source code with the help of

Looking for a way to extract the source code of a URL using Selenium? this.setUp("http://www.remax.com/", "*firefox"); selenium.open("/404/index.aspx?aspxerrorpath=/public/pages/searchresults.aspx"); slenium.click("link=Find a RE/MAX Office"); selenium.wa ...

Trigger an AWS Lambda function from an Angular application utilizing HTTP requests

After successfully creating, building, and deploying an AWS Lambda with the AWS SDK for Java, I encountered no issues while testing it using the AWS console. Now, my goal is to trigger the Lambda function whenever a user clicks a button in my Angular appl ...

JPA versus JavaBeans validation (JSR 303) versus our custom approach: Automatically truncating fields prior to persistence

Being new to JPA and JSR 303, I have encountered a situation where some fields in the database have fixed lengths. It seems that JPA prevents me from persisting an entity with a field size larger than allowed in the database, while using the @Column annota ...

What is the process for creating a report in Selenium WebDriver with Java?

Currently, I am working with Java and Selenium WebDriver. I am looking for ways to create a report in Selenium WebDriver using Java without relying on JUnit or TestNG reports. Can someone offer assistance? Your help would be greatly appreciated! Thank yo ...

Deliver a Java Applet using Laravel

I'm currently working on incorporating a Java applet into my Laravel application and I'm looking for guidance. My plan is to start off with a straightforward approach by using the applet tag directly in a view: <applet code="OHLib.class" wid ...

create an instance of the class provided as an argument

I wanted to design a system for creating different types of Plants (inspired by plants vs zombies) in an organized way. To simplify the addition of new plant Types, I aimed to make the cost and damage of each plant static so it could be set once for all Pl ...

Adjust the color of the entire modal

I'm working with a react native modal and encountering an issue where the backgroundColor I apply is only showing at the top of the modal. How can I ensure that the color fills the entire modal view? Any suggestions on how to fix this problem and mak ...

Storing a 2D array in HSQLDB for safekeeping

Can someone guide me on how to save a two-dimensional array in a database using HSQLDB? I have also attempted to save HashMap or ArrayList collections but without success. public MyEntity { String id; double[][] data; ArrayList arrayValue; } ...

Different categories combined into a singular category

Trying to define a type that can be one of two options, currently attempting the following: type TestConfig = { file: string; name: string; } type CakeConfig = { run: string; } type MixConfig = { test: TestConfig | CakeConfig }; const typeCheck: M ...

Angular Material Table with Pagination: Fetch data from server by triggering API call upon clicking on the "Next Page

When working with MatPaginator in conjunction with mat-table, what is the most effective approach for handling the next page click event? I have developed a custom DataSource with connect() and disconnect() functions. Is it necessary to explicitly manage ...

Is there a way for me to identify which item has been unselected from the dropdown menu?

I have a dropdown menu where users can select the languages they are proficient in, along with their proficiency level and years of experience. The user may select multiple choices but can also deselect options by mistake. Additionally, I am encountering ...