And*_*cus 10 json typescript angular
在我的服务器端,我有一个包含HashMap的Java对象.我想将它序列化为JSON,将其返回到我的Angular2客户端并将其用作那里的Map/Dictionary.
这是班级:
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;
}
Run Code Online (Sandbox Code Playgroud)
}
这是我在客户端收到的JSON:
{"timestamp":"","message":"Test","status":"1","parameters":{"myKey":"Value","mySecondKey":"Another Value"}}
Run Code Online (Sandbox Code Playgroud)
这是我收到的Angular2 http调用:
this.http.post(this.uploadURL, formData).map((res:Response) => res.json() as FileUploadResult).catch(this.handleError);
Run Code Online (Sandbox Code Playgroud)
客户端上的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;
}
}
Run Code Online (Sandbox Code Playgroud)
通过在http.map调用中使用"as FileUploadResult",我希望在我可以调用的地方获得一个对象result.getParameters().get("myKey").但那并没有发生.我得到一个未指定的对象,其中唯一有效的调用是result.parameters.myKey.有没有办法实现我想要的,并将JSON对象转换为FileUploadResult,包括Angular2映射?
Nit*_*mer 13
调用的结果res.json()是一个javascript对象,可以这样访问:
let json = res.json();
console.log(json["timestamp"]);
console.log(json.message);
Run Code Online (Sandbox Code Playgroud)
在typescript中描述这样一个对象的方法是使用接口(或类型别名):
interface JsonResponse {
timestamp: string;
message: string;
status: string;
parameters: { [name: string]: string };
}
Run Code Online (Sandbox Code Playgroud)
如果您想将此对象转换为您的类,您需要执行以下操作:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
(游乐场代码)
| 归档时间: |
|
| 查看次数: |
14959 次 |
| 最近记录: |