2011-12-15 90 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读它?