Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript Map to Java Map

I want to call java Api from my angular 2 app.I used typescript Map to send request in java app.
My RestEndpoint in java is like this:

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

I got this error when i try to use 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]

In postman i use this as raw body and it 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);
}
like image 706
M1r1 Avatar asked Jan 09 '18 12:01

M1r1


1 Answers

Please ensure, that your actual request body, starts with { tag, not: [. As you have written, in Postman you wrap your request with { }, whereas error message:

[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]

suggests, that your actual request is wrapped with [ ] tags

EDIT (to answer your first comment): Translate your Map into Object. For example you can achieve it with this function:

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

Then provide the result of your transformation into the http.post line

Edit 2 The above answer will work if you are using es6, if you are using es5 u can try using a dictionary like this

let map:{ [name: string]: number }={};
map["key1"]=value1;
map["key2"]=value2;
like image 85
Tinki Avatar answered Nov 15 '22 14:11

Tinki