Java Map for JSON before Typescript Map

on my server side I have a Java object containing a HashMap. I want to serialize it to JSON, return it to the Angular2 client and use it as a Map / Dictionary.

Here's the class:

public class FileUploadResult { String timestamp; String message; String status; HashMap<String, String> parameters; public FileUploadResult(String status, String message, String timestamp, HashMap parameters) { this.status = status; this.message = message; this.timestamp = timestamp; this.parameters = parameters; } 

}

Here is the JSON I get on the client side:

 {"timestamp":"","message":"Test","status":"1","parameters":{"myKey":"Value","mySecondKey":"Another Value"}} 

Here is my Angular2 http call invocation:

 this.http.post(this.uploadURL, formData).map((res:Response) => res.json() as FileUploadResult).catch(this.handleError); 

FileUploadResult on the client is as follows:

 export class FileUploadResult { status: string; timestamp: string; message: string; parameters: Map<string, string>; constructor() { this.parameters = new Map<string, string>(); } addParameter(key: string, value: string) { this.parameters.set(key, value); } getParameters() { return this.parameters; } } 

Using "like FileUploadResult" in the http.map call, I was expecting to get an object where I can call result.getParameters().get("myKey") . But this does not happen. I get an undefined object where a single call to result.parameters.myKey . Is there a way to achieve what I want and pass the JSON object to FileUploadResult, including the Angular2 map?

+9
source share
2 answers

The result of calling res.json() is a javascript object that can be accessed like this:

 let json = res.json(); console.log(json["timestamp"]); console.log(json.message); 

A way to describe such an object in typescript is to use an interface (or type alias):

 interface JsonResponse { timestamp: string; message: string; status: string; parameters: { [name: string]: string }; } 

If you want to convert this object to your class, you need to do something like:

 class FileUploadResult { status: string; timestamp: string; message: string; parameters: Map<string, string>; constructor(json: JsonResponse) { this.status = json.status; this.timestamp = json.timestamp; this.message = json.message; this.parameters = new Map<string, string>(); Object.keys(json.parameters).forEach(key => { this.addParameter(key, json.parameters[key]); }); } addParameter(key: string, value: string) { this.parameters.set(key, value); } getParameters() { return this.parameters; } } 

( code on the playground )

+10
source

A little later, but you can use my library to generate typewriting models starting with Java.

I also added the ability to use Angular's coding style, and I'm ready to offer support for change requests :)

Check it out here JavaModel-Converter

0
source

Source: https://habr.com/ru/post/1261400/


All Articles