2016-12-16 52 views
5

我的服务器端我有一个包含HashMap的Java对象。我想将它序列化为JSON,并将其返回给我的Angular2客户端,并将其用作Map/Dictionary。Java地图到JSON到手稿地图

这里的类:

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; 
    } 
} 

通过使用“作为FileUploadResult”在http.map电话,我希望得到我在哪里可以打电话result.getParameters().get("myKey")的对象。但这并没有发生。我得到一个未指定的对象,其中唯一的调用是result.parameters.myKey。有没有办法实现我想要的,并将JSON对象投射到包含Angular2地图的FileUploadResult?

+0

相同http://stackoverflow.com/questions/29758765/json-to-typescript-class-instance? –

+0

@RyanCavanaugh不幸的不是。我不提前知道钥匙。 – Androidicus

回答

6

主叫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; 
    } 
} 

code in playground