2011-12-15 93 views
0

我想構建這樣一個JSON有效載荷:JSON有效載荷建設的Android

{ 
    "aps": { 
     "badge": 15, 
     "alert": "Hello from Urban Airship!", 
     "sound": "cat.caf" 
    } 
} 

我這個東西的嘗試:

 JSONObject json = new JSONObject(); 

     JSONObject badge=new JSONObject(); 
     JSONObject alert=new JSONObject(); 
     JSONObject sound=new JSONObject(); 


     badge.put("badge",15); 
     json.put("aps",badge); 
     sound.put("sound",getResources().openRawResource(R.raw.cat)); 
     json.put("aps",alert); 
     alert.put("alert", "Hello from Uday!"); 
     json.put("aps",sound); 

,但它充分有效載荷獲取:當我打印

am越來越像這樣的有效載荷的一半:

{"aps":{"sound":"cat.caf"}}

其壓倒一切,但

以正確的方式是如何

感謝

回答

1

我不確定你在找什麼,但考慮到你想創建一個JSON字符串。

 try { 
      JSONObject json = new JSONObject(); 
      JSONObject aps = new JSONObject(); 

      aps.put("badge", 15); 
      aps.put("alert", "Hello from Urban Airship!"); 
      aps.put("sound", "cat.caf"); 
      Log.d("my json string", json.put("aps", aps).toString(1)); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
+0

是的,我想構建那個JSON有效載荷.. – Udaykiran 2011-12-16 05:24:12

1

openRawResource()返回InputStream ..你可能想嘗試使用InputStreamReader讀它?