在我的服务器端,我有一个包含hashmap的Java对象。我想将其序列化为JSON,将其返回到我的Angular2客户端,然后将其用作地图/词典。
这是类:
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;
}
}
这是我在客户端收到的JSON:
{"timestamp":"","message":"Test","status":"1","parameters":{"myKey":"Value","mySecondKey":"Another Value"}}
这是我的接收angular2 http呼叫:
this.http.post(this.uploadURL, formData).map((res:Response) => res.json() as FileUploadResult).catch(this.handleError);
客户端上的fileuploadresult看起来像:
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;
}
}
通过在http.map调用中使用" as as fileuploadresult",我希望可以在可以调用 result.getParameters().get("myKey")
的位置获取一个对象。但这没有发生。我得到一个未指定的对象,其中唯一有效的调用是result.parameters.myKey
。有没有办法实现我想要的东西并将JSON对象施加到fileuploadresult,包括Angular2 Map?
调用res.json()
的结果是一个可以像这样访问的JavaScript对象:
let json = res.json();
console.log(json["timestamp"]);
console.log(json.message);
在打字稿中描述这种对象的方法是使用接口(或键入别名):
interface JsonResponse {
timestamp: string;
message: string;
status: string;
parameters: { [name: string]: string };
}
如果要将此对象转换为类,则需要做类似:
的事情。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;
}
}
(操场上的代码)
class FileUploadResult {
parameters: Record<string, string> = {};
addParameter(key: string, value: string) {
this.parameters[key] = value;
}
}
您可以这样使用它
const abc = new FileUploadResult();
abc.addParameter('hi', 'hello');
console.log(abc.parameters); // will log {hi: "hello"}
https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkt