2016-12-16 77 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