2014-02-10 68 views
0

好吧,我以前用POST工作過,但是我從來不需要POST數組。 (真的)如何使用POST與JSONArray

這是POST形式:

{ 

    "about": "about me", 
    "sports": [ 
    { 
      "id": 1, 
      "level": 3 

    }, 

    { 

      "id": 2, 
      "level": 4 

    } 

    ] 

} 

所以我要送一個JSONObject與「關於」鍵和值,和「體育」 JSONArray,這可能是空了。

我試過如下:

1.

List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(); 
    nameValuePair.add(new BasicNameValuePair("about", "Lorem ipsum about me")); 
    nameValuePair.add(new BasicNameValuePair("sports", "[]")); 

2.

List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(); 
     nameValuePair.add(new BasicNameValuePair("about", "Lorem ipsum about me")); 
     nameValuePair.add(new BasicNameValuePair("sports", new ArrayList<NameValuePair>())); 
                ///Of course its silly it doesnt work at all 

所以我的問題是如何實現這一目標POST形式?

我的帖子:

HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost(url); 
httppost.addHeader("Content-Type", "application/json"); 
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
HttpResponse httpResponse = httpclient.execute(httppost); 
+0

UrlEncodedFormEntity不是JSON。使用StringEntity和JSONObject.toString()。 – njzk2

回答

1

在這裏,我手動建立起來的JSONObject的你:

try{ 
    JSONObject attr1 = new JSONObject("{\"id\": 1, \"level\":3 }"); 
    JSONArray sports = new JSONArray(); 
    sports.put(attr1); 
    //sports.put(attr2); and so on 
    JSONObject yourObject = new JSONObject("{\"about\": \"About me\"}"); 
    yourObject.put("sports", sports); 

    String url = yourObject.toString(); 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost(url); 
    HttpResponse httpResponse = httpclient.execute(httppost); 

}catch(Exception e){ 
} 

正如你所看到的,我已經建立了從字符串的JSON的某些部分,但你也可以創建一個空對象並填充數據(正如我在jsonarray中所做的那樣)