2017-08-17 88 views
0

我知道Android中的jsonparsing。 如果下面是JSON響應如何在打字稿中做JSONParsing

{ 
    "contacts": [ 
     { 
       "id": "c200", 
       "name": "Ravi Tamada", 
       "email": "[email protected]", 
       "address": "xx-xx-xxxx,x - street, x - country", 
       "gender" : "male", 
       "phone": { 
        "mobile": "+91 0000000000", 
        "home": "00 000000", 
        "office": "00 000000" 
       } 
     }, 
     { 
       "id": "c201", 
       "name": "Johnny Depp", 
       "email": "[email protected]", 
       "address": "xx-xx-xxxx,x - street, x - country", 
       "gender" : "male", 
       "phone": { 
        "mobile": "+91 0000000000", 
        "home": "00 000000", 
        "office": "00 000000" 
       } 
     }, 

    ] 
} 

我們以前從這樣

JSONObject jsonObj = new JSONObject(jsonStr); 


         JSONArray contacts = jsonObj.getJSONArray("contacts"); 


         for (int i = 0; i < contacts.length(); i++) { 
          JSONObject c = contacts.getJSONObject(i); 

          String id = c.getString("id"); 
          String name = c.getString("name"); 
          String email = c.getString("email"); 
          String address = c.getString("address"); 
          String gender = c.getString("gender"); 

          JSONObject phone = c.getJSONObject("phone"); 
          String mobile = phone.getString("mobile"); 
          String home = phone.getString("home"); 
          String office = phone.getString("office"); 
} 
} 

因此,對於相同的JSON響應如何讓打字稿數據(Angular2)的反應得到的數據。 我對Angular2很新穎。任何人都可以幫助我。

回答

2

在TypeScript中,它與Javascript中的相同,您使用JSON.parse(yourString)解析JSON字符串,並使用JSON.stringify將您的javascript對象/數組轉換爲JSON字符串。

JSON.parse返回一個普通對象,因此您可以使用點符號(即myObject.myProperty)或數組表示法(即myObject['myProperty'])訪問其屬性。

比照MDN

+0

的OP用於Java的不是JS – Vega

1

打字稿是JavaScript的一個超集。這意味着任何有效的Javascript也是有效的Typescript。 JavaScript有一個全球性的,內置的解析器:

let jsonString='{"hello": "World"}'; 
 

 
let myObject= JSON.parse(jsonString); 
 

 
console.log(myObject.hello);

它也適用於其他方式:

let obj= { 
 
    key1: 1, 
 
    key2: "Hi there", 
 
    key3: new Date() 
 
    } 
 
    
 
    console.log(JSON.stringify(obj));

+0

該OP被用於Java而非JS – Vega

+0

所以我解釋瞭如何用Javascript/Typescript做到這一點,我沒有看到你的觀點 –

+0

我的remarque本身並不是關於答案的,但'這意味着任何有效的Javascript也是有效的Typescript'。 :)我的意思是可能OP不用於JS – Vega