2014-02-10 106 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中所做的那样)