通过HTTPpost以定义的格式发送JSONObject?

时间:2012-04-04 20:32:52

标签: android json http-post

     {
     who: 'troll_new3',
     visibility: 'public',

     poll: {
     title: 'Favourite game?',
     des_content_type: 'text',
     description: 'I want to know which game you like!', 
     options_type: 'text',
     comments_enabled: true,  
     poll_method: 'list',     
     }   
    }

我需要这个作为JSONObject的格式来接收。

这是我正在实施的代码:

obj=new JSONObject();
try {
    obj.put("options_type", "text");        
    obj.put("description", pd.getText().toString());
    obj.put("des_content_type", "text");
    obj.put("title", pt.getText().toString());
    obj.put("comments_enabled", "false");
    obj.put("poll_method",str);

} catch (JSONException e1) {
    //TODO Auto-generated catch block
    Log.v("my","error");
    e1.printStackTrace();
}

obj1=new JSONObject();
try {           
    obj1.put("who", facebookId);        
    obj1.put("visiblity", "public");
    obj1.put("poll", obj.toString());

} catch (JSONException e1) {
    //TODO Auto-generated catch block
    Log.v("my","error");
    e1.printStackTrace();
}
StringEntity se=null;
try {
    se = new StringEntity(obj1.toString());
} catch (UnsupportedEncodingException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}  

try{
    se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 
    httppost.setEntity(se);

    httppost.setHeader("Accept", "application/json");
    httppost.setHeader("Content-type", "application/json");
    Log.v("myapp", "works till here. 2");
    try {
        HttpResponse response = httpclient.execute(httppost);

        Log.v("myapp", "works till here. 3");

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
} catch (Exception e) {
    e.printStackTrace();
}

我希望在输出中获得预定义的JSON格式。 {poll:'{“title”:“dsfg”,“des_content_type”:“text”,“poll_method”:“list”,“options_type”:“text”,“comments_enabled”:“false”,“description”:“ Dfg“}',   visiblity:'public',   谁:'1758281246'}

请有人帮助我。

1 个答案:

答案 0 :(得分:0)

你的问题就在这里。

obj1=new JSONObject();           
obj1.put("who", facebookId);        
obj1.put("visiblity", "public");
obj1.put("poll", obj.toString());

obj.toString()添加到obj时,请勿致电obj1。将其保留为JSONObject,以便类可以正确处理内部格式。